Number of Digits

Easy
0/40
Average time to solve is 8m
profile
Contributed by
41 upvotes
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’.
Detailed explanation ( Input/output format, Notes, Images )
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
Sample Input 1 :
2
89
870
Sample Output 1 :
2
3
Explanation Of Sample Input 1 :
In test case ā€˜1’. There are ā€˜2’ digits present in ā€˜89’ that is ā€˜8’ and ā€˜9’. So the answer is ā€˜2’.
In test case ā€˜2’. There are ā€˜3’ digits present in ā€˜870’ that is ā€˜8’, ā€˜7’ and ā€˜0’. So the answer is ā€˜3’.
Sample Input 2 :
2
240
1
Sample Output 2 :
3
1
Hint

How many times we can remove one digit from it? 

Approaches (2)
Iterative Solution

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’.
Time Complexity

O(log10(X)). Where ā€˜X’ is the input long integer.

 

As we are deleting ā€˜1’ digit every time when we enter in the while loop. So ā€˜number of digits’ will be the time complexity that will be O(log10(X)).

Space Complexity

O(1).

As we are maintaining a constant variable to store the answer, the space complexity will be O(1).

Code Solution
(100% EXP penalty)
Number of Digits
Full screen
Console