Als kleines Nebenthema hatte ich heute mit der Aufgabe zu tun, die Anzahl der Stellen einer Zahl (positive, ganze Zahl >=1) zu bestimmen. Mir fiel ein, dass ich das schonmal “irgendwie mit dem Logarithmus” gemacht habe.
Nach ein wenig Reflektieren und Googeln kamen folgende Lösungsmöglichkeiten in Betracht, jede für sich mit unterschiedlichen Ecken und Kanten. Da mein Problem “gelöst” ist (es ist an der geforderten Stelle völlig zeitunkritisch), stelle ich hier mal die verschiedenen Möglichkeiten rein akademisch zur Diskussion. Vielleicht gibt es ja auch noch mehr.
public static void main(String[] args) {
greetings();
for (int i=1; i<101; ++i) {
proof(i);
}
proof(101);
proof(999);
proof(1000);
proof(1001);
proof(9999);
proof(10000);
proof(10001);
proof(99999);
proof(100000);
proof(100001);
proof(999999);
proof(1000000);
proof(1000001);
proof(9999999);
proof(10000000);
proof(10000001);
proof(99999999);
proof(100000000);
proof(100000001);
proof(999999999);
proof(1000000000);
proof(1000000001);
proof(Integer.MAX_VALUE);
}
private static void greetings() {
System.out.println("n Log Calc If String Gleich");
}
private static void proof(int number) {
int d1 = digitCountLog(number);
int d2 = digitCountCalc(number);
int d3 = digitCountIf(number);
int d4 = digitCountString(number);
boolean equal = d1 == d2 && d2 == d3 && d3 == d4;
System.out.println(number + " " + d1 + " " + d2 + " " + d3 + " "
+ d4 + " " + equal);
}
public static int digitCountLog(int input) {
return ((int) Math.log10(input)) + 1;
}
public static int digitCountCalc(int input) {
int digits = 1;
while (input > 9) {
input /= 10;
++digits;
}
return digits;
}
public static int digitCountIf(int input) {
if (input < 100000) {
if (input < 1000) {
if (input < 100) {
if (input < 10) {
return 1;
}
return 2;
}
return 3;
}
if (input < 10000) {
return 4;
}
else {
return 5;
}
}
if (input < 100000000) {
if (input < 10000000) {
if (input < 1000000) {
return 6;
}
return 7;
}
return 8;
}
if (input < 1000000000) {
return 9;
}
else {
return 10;
}
}
public static int digitCountString(int input) {
return Integer.toString(input).length();
}
}