Last Updated: 12 Apr, 2022

Number of Digits

Easy
Asked in companies
OracleTravClanNewgen Software Technologies Pvt.Ltd

Problem statement

Ninja want to add coding to his skill set so he started learning it. On the first day, he stuck to a problem in which he has given a long integer ‘X’ and had to count the number of digits in it.

Ninja called you for help as you are his only friend. Help him to solve the problem.

EXAMPLE:
Input: 'X' = 2

Output: 1

As only one digit is ‘2’ present in ‘X’ so answer is ‘1’.
Input Format :
The first line will contain the integer 'T', denoting the number of test cases.

Each test case contains a single long integer ‘X’. 
Output format :
For each test case, print the number of digits in the given integer ‘X’.
Note :
You don't need to print anything. It has already been taken care of. Just implement the given function.
Constraints :
1 <= 'T' <= 1000
1 <= ‘X’ <= 10^18
Time Limit: 1 sec

Approaches

01 Approach

Approach: 

 

We will remove the least significant digit from the given integer by dividing it by 10 until the number does not become zero. The number of times we can perform the above operation is the answer.
 

 

Algorithm :  
 

  • Maintain a variable ‘ANS’.
  • Now start a while loop
  • While ‘(‘X’ != ‘0’ )’
    • ‘ANS+=1’
    • ‘X’=X/10
  • Return ‘Ans’.

02 Approach

Approach: 


This approach is the shorter version of the iterative approach. We know that number of times we can delete the least significant digit from the number is the same as the number of times it can divide ‘10’. So the answer will be simply ‘floor( log10(X) + 1 )’.

 

Algorithm :  

 

  • Return floor( log10(X)+1 )