HydrogenUranium :
How do I shift to left in last 2 row in my output Floyd's triangle ? Here is my output:
1
21
421
8421
168421
32168421
Expected output:
1
21
421
8421
168421
32168421
Here is my code :
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(" ");
}
Thank you
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());
}
And a more generic example:
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();
}
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=323044&siteId=1