Skip to content

Count Digits

Method-1

countDigits.cpp
#include <bits/stdc++.h>
using namespace std;

int countDigits(int n){
    int count = 0;
    while(n > 0) {
        n /= 10;
        count++;
    }
    return count;
}

int main() {
    int n;
    cin >> n;
    cout << countDigits(n);
    return 0;
}

Input: 5432
Output: 4

Method-2

countDigits.cpp
#include <bits/stdc++.h>
using namespace std;

int countDigits(int n){
    int count = floor(log10(n) + 1);
    return count;
}

int main() {
    int n;
    cin >> n;
    cout << countDigits(n);
    return 0;
}

Input: 5432
Output: 4