Find number of digits in a number
Given an integral number N. The task is to find the count of digits present in this number. Lets say n = 2020, number of digits in 2020 = 4 and digits are 2,0,2,0
A simple solution is..
- Check if number n != 0
- increment count of digits by 1 if n !=0
- reduce number by dividing it with 10
- repeat above steps, until n is reduced to 0
1//iterative
2int countDigits(long n){
3 int count = 0;
4 while(n > 0){
5 n = n/10;
6 ++count;
7 }
8 return count;
9} // TC: O(digitsCount), SC: O(1)
10
11//recursive
12int countDigits(long n){
13 if(n==0) return 1;
14 return 1+ countDigits(n/10);
15} // TC: O(digitsCount), SC: O(digitsCount)
Another approach :
Convert number to string and find string length
1 public static int countDigits(long n) {
2 String num = Long.toString(n);
3 return num.length();
4 }//TC: O(1), SC:O(1)
A better solution..
Use Logarithmic approach to solve this problem. This can be easily obtained by using a formula
number of digits in N = log10(N) + 1. log(123) = 2.08 => 2.08+1 = 3.08 floor(3.08) is 3.
1 public static long countDigits(long n) {
2 if (n == 0)
3 return 0;
4 return (int) Math.floor(Math.log10(n) + 1);
5 } //TC: O(1), SC:O(1)
Palindrome Number
check whether a given number is palindrome or not. Eg: n = 106601 -> true, n = 84348 -> true, n = 8 -> true. n= 21 -> false, n = 1789 -> false.
1bool isPalindrome(int n){
2 int rev = 0;
3 int temp = n;
4 while(temp!=0){
5 int lastDigit = temp%10;
6 rev = rev * 10 + lastDigit;
7 temp/=10;
8 }
9 return(rev==n);
10} // TC: O(n)