HydrogenUranium:
¿Cómo me muevo a la izquierda en la última fila 2 en mi salida del triángulo de Floyd? Aquí está mi salida:
1
21
421
8421
168421
32168421
Rendimiento esperado:
1
21
421
8421
168421
32168421
Aquí está mi código:
for(int i=0; i<=5; ++i) {
//total of space
int n=6-i;
//print space
while(n>0) {
System.out.print(" ");
n--;
}
//print number
for(int j=i; j>=0; j--) {
System.out.print((int)Math.pow(2, j));
}
System.out.println(" ");
}
Gracias
fedup:
int lineLength = 8;
for (int i = 0; i <= 5; ++i) {
//print number
StringBuilder sb = new StringBuilder();
for (int j = i; j >= 0; j--) {
sb.append((int) Math.pow(2, j));
}
//print space
for (int spaces = lineLength - sb.length(); spaces > 0; spaces--) {
System.out.print(" ");
}
System.out.println(sb.toString());
}
Y un ejemplo más genérico:
public static void main(String[] args) {
int numbersToCompute = 10;
int lineLength = floydsNumber(numbersToCompute).length();
for (int i = 0; i <= numbersToCompute; ++i) {
String floydsNumber = floydsNumber(i);
for (int spaces = lineLength - floydsNumber.length(); spaces > 0; spaces--) {
System.out.print(" ");
}
System.out.println(floydsNumber.toString());
}
}
private static String floydsNumber(int i) {
StringBuilder sb = new StringBuilder();
for (int j = i; j >= 0; j--) {
sb.append((int) Math.pow(2, j));
}
return sb.toString();
}