import math
def countDigits(n: int) -> int:
# Write your code here
return int(math.log10(n)+1)
passProblem of the day
You are given a number 'n'.
Return number of digits in ‘n’.
Input: 'n' = 123
Output: 3
Explanation:
The 3 digits in ‘123’ are 1, 2 and 3.
The first line of input contains an integer ‘n’.
Return an integer as described in the problem statement.
You don’t need to print anything, it has already been taken care of, just complete the given function.
121
3
There are 3 digits in 121 are 1,2 and 1.
38
2
The expected time complexity is O(log n).
1 <= ‘n’ <= 10^9
Convert the integer to a string.
Approach:
We can convert the integer to a string, then return the length of the string.
The steps are as follows:
function countDigits(int n)
O(log(n)), where ‘n’ is the given number.
We are iterating through all the digits of ‘n’ and there are log(n) such digits.
Hence, the time complexity is O(log(n)).
O(log(n)), where ‘n’ is the given number.
We are using extra string ‘s’ of length log(n).
Hence, the space complexity is O(log(n)).
Interview problems
Easy peasy python solution
import math
def countDigits(n: int) -> int:
# Write your code here
return int(math.log10(n)+1)
passInterview problems
VERY SMALL CODE || C++ 🔥
int countDigits(int n){
int count = 0;
while(n>0){
count = count +1;
n=n/10;
}
return count;
}
Interview problems
Number of digits
int countDigits(int n){
int count = 0;
while(n>0){
int lastdigit = n%10;
count = count +1;
n = n/10;
}
return count;
}
Interview problems
Number of digits
int countDigits(int n){
// Write your code here.
int count = 0;
while(n>0)
{
count = count+1;
n = n/10;
}
return count;
}
Interview problems
JAVA Solution
import java.util.*;
public class Solution {
public static int countDigits(int n) {
// Handle the special case where n is 0
if (n == 0) {
return 1;
}
// Calculate the number of digits
int count = (int)(Math.log10(n) + 1);
return count;
}
}
Interview problems
JAVA EASY SOLUTION
public class Solution {
public static int countDigits(int n){
// Write your code here.
int count = 0;
while (n > 0) {
n = n / 10 ;
count++;
}
return count;
}
}
Interview problems
how to run this code in java
public class Solution {
public static int countDigits(int n){
int lastdigit=0;
int count=0;
while(n>0)
{
lastdigit=n%10;
count=count+1;
n=n/10;
}
return count;
}
}
Interview problems
[C++] All Tests passed
int countDigits(int n){
// Write your code here.
// corner cases
if(n == 0) return 1;
int count = 0;
while(n > 0){
n = n / 10;
count++;
}
return count;
}Interview problems
Easiest One Line solution
int countDigits(int n){
// Write your code here.
int count = to_string(n).length();
return count;
}
Interview problems
C++ Solution || All test case passed || Time Complexity: O(1)
int countDigits(int n){
return log10(n) + 1;
}