Problem:
Given an integer, find the number of digits in it.
Example:
Input: 1234
Output: 4
Input: -789435
Output: 6
Approach 1) Iterative
Every time we divide a number by 10, the number of digits reduces by 1. So, we can count it until the number becomes 0.
public class Solution {
int countDigits(int n){
int ans = 0;
while(n!=0){
n/=10;
ans++;
}
return ans;
}
public static void main(String[] args){
int num = 12345;
System.out.println(countDigits(num));
}
}
Time complexity: O(number of digits)
Space complexity: O(1)