Digits#2

Digits (Editorial)

This problem asks you to find the number of digits in a positive integer number. There are two approaches 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 until it reaches . The number of iterations in the loop would be the answer.

For example, if the number is , your program will perform 5 iterations:

  1. with n = 12345

  2. with n = 1234

  3. with n = 123

  4. with n = 12

  5. with n = 1

After division in the 5th iteration, will become and the loop will stop.

In this solution you have to make sure that the edge case when n = 0 is handled correctly. You can add an if before the loop or perform the 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 straightforward, but you must ensure the string does not contain any extra symbols, for example the newline symbol \n or the carriage return symbol \r. You can handle these symbols by using the 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))