Skip to content

Instantly share code, notes, and snippets.

@carousel
Created January 31, 2020 17:17
Show Gist options
  • Save carousel/9325158c03b9924593b1b140b9b9f7ae to your computer and use it in GitHub Desktop.
Save carousel/9325158c03b9924593b1b140b9b9f7ae to your computer and use it in GitHub Desktop.
Count number of digits in integer with Java
public static int stringBased(int number) {
return String.valueOf(number).length();
}
public static int logarithmBased(int number) {
return (int) Math.log10(number) + 1;
}
public static int repeatedMultiplication(int number) {
int length = 0;
long temp = 1;
while (temp <= number) {
length++;
temp *= 10;
}
return length;
}
public static int powersOfTwo(int number) {
int length = 1;
if (number >= 100000000) {
length += 8;
number /= 100000000;
}
if (number >= 10000) {
length += 4;
number /= 10000;
}
if (number >= 100) {
length += 2;
number /= 100;
}
if (number >= 10) {
length += 1;
}
return length;
}
public static int divideAndConquer(int number) {
if (number < 100000) {
if (number < 100) {
if (number < 10) {
return 1;
} else {
return 2;
}
} else {
if (number < 1000) {
return 3;
} else {
if (number < 10000) {
return 4;
} else {
return 5;
}
}
}
} else {
if (number < 10000000) {
if (number < 1000000) {
return 6;
} else {
return 7;
}
} else {
if (number < 100000000) {
return 8;
} else {
if (number < 1000000000) {
return 9;
} else {
return 10;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment