java金字塔显示_Java中的金字塔模式

bd96500e110b49cbb3cd949968f18be7.png

It was so hard to ask such a newbie question on this advanced site. But after so much tries and even loosing my hope i was forced to bring my self here. I am not been able to print the following pattern:

1

1 2 1

1 2 4 2 1

1 2 4 8 4 2 1

1 2 4 8 16 8 4 2 1

1 2 4 8 16 32 16 8 4 2 1

But with my tiresome efforts i reached the following:

public static void main(String[] args) {

int num = 1;

for (int i = 0; i < 15; i++) {

for (int j = 0; j < 15 - i; j++) {

System.out.print(" ");

}

for (int k = 0; k <= i; k++) {

System.out.print(num + " ");

}

System.out.println();

}

}

1

1 1

1 1 1

1 1 1 1

1 1 1 1 1

1 1 1 1 1 1

1 1 1 1 1 1 1

1 1 1 1 1 1 1 1

1 1 1 1 1 1 1 1 1

1 1 1 1 1 1 1 1 1 1

1 1 1 1 1 1 1 1 1 1 1

1 1 1 1 1 1 1 1 1 1 1 1

解决方案

Here ya go

public static void main(String[] args) {

int max = 6;

int padLength = (int) Math.ceil(Math.log10(Math.pow(2, max) + 1)) + 2;

for (int i = 0; i < max; i++) {

for (int j = 1; j < max - i; j++) {

System.out.print(pad(" ", padLength));

}

for (int k = 0; k <= i; k++) {

System.out.print(pad(Math.pow(2, k), padLength));

}

for (int k = i - 1; k >= 0; k--) {

System.out.print(pad(Math.pow(2, k), padLength));

}

System.out.println();

}

}

public static String pad(double d, int l) {

Integer i = (int) d;

return pad(i.toString(), l);

}

public static String pad(String s, int l) {

return String.format("%-" + l + "s", s);

}

Explanation

int padLength = (int) Math.ceil(Math.log10(Math.pow(2, max) + 1)) + 2;

Math.pow(2,max) - Gives me maximal number I will have to display

Math.ceil(Math.log10(number + 1)) - I use this to determine length of string representation of specific number. Please refer to wikipedia to check what logarithm is. I add 1 to skip edge case when number is exact power of 10 e.g. log10(10)->1 (this will never occur in task specified in question, it's just for purity of solution). Ceil just rounds number up.

+2 - minimum gap between two numbers is specified example was 2 spaces long so I just add this

You could use here Integer.toString(((int)Math.pow(2, max))).length()+2 but it's not as pretty :)

return String.format("%-" + l + "s", s);

First I build format string that looks like e.g. %-3s, which means print String with minimum length of 3, padding on the right. Second argument is the String I want to print. Refer to documentation

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值