Created
November 21, 2014 00:57
-
-
Save deyindra/67625b8e149b023c5a41 to your computer and use it in GitHub Desktop.
Count of Digit in a 32 bit integer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
public class CountDigit { | |
public static final long[] ARRAY = { | |
9L, | |
99L, | |
999L, | |
9999L, | |
99999L, | |
999999L, | |
9999999L, | |
99999999L, | |
999999999L, | |
9999999999L | |
}; | |
//O(log(N) complexity | |
public static int countDigit(int number){ | |
int count=0; | |
boolean isNegative= false; | |
//Storing in long in order overcome numeric overflow | |
// when one will do the Math.abs on Integer.MIN_VALUE | |
long longNum = number; | |
if(longNum<0){ | |
isNegative = true; | |
longNum = Math.abs(longNum); | |
} | |
count = Arrays.binarySearch(ARRAY,longNum); | |
if(count<0){ | |
count = -count; | |
}else{ | |
count = count+1; | |
} | |
if(isNegative){ | |
count++; | |
} | |
return count; | |
} | |
public static void main(String[] args){ | |
//Return 2 | |
System.out.println(countDigit(11)); | |
//Return 3 | |
System.out.println(countDigit(-11)); | |
//Return 1 | |
System.out.println(countDigit(9)); | |
//Return 3 | |
System.out.println(countDigit(-99)); | |
//Return 10 | |
System.out.println(countDigit(Integer.MAX_VALUE)); | |
//Return 11 | |
System.out.println(countDigit(Integer.MIN_VALUE)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment