Editorial
This problem asks you to find number of digits in a positive integer number. There are two appraoches to solve it: you can read input as a number and divide it by until you get , the number of the divisions will be the answer, or you can read input as a string, the length of the string will be the answer.
Using number
This solution requires you to implement a simple while
loop. In each iteration you will have to divide the number by and round down the value util it reaches . Number of iterations in the loop would be the answer.
For example, if the number is , your program will perform 5 iterations:
with
with
with
with
with
After division in the 5th iteration the will become and the loop will stop.
In this solution you have to make sure edge case when is handled correctly. You can add an if
before the loop or perform first iteration without checking .
In C++,
#include<iostream> using namespace std; int main() { int n = 0; cin>>n; int i = 0; do { n /= 10; // since n is an integer it will be automatically rounded down i++; // increase number of iterations (equals to number of digits) } while(n != 0); // check n value in the end cout<<i<<endl; return 0; }
In Python,
n = int(input()) if n == 0: print(1) # number 0 has a single digit else: i = 0 while n != 0: n = n // 10 # divide n by 10 and round down i = i + 1 # increase number of iteartions (equals to number of digits) print(i)
Using string
This solution requires you to read input as a string and output the length of the string. It's very straight forward, but you must ensure the string does not contain any extra symbols, for example end line symbol \n
or carriage return symbol \r
. You can handle these symbols by using trim
function in your programming language.
In C++,
#include<iostream> using namespace std; int main() { string n; cin>>n; cout<<n.length()<<endl; return 0; }
In Python,
n = input() print(len(n))