如何改进/减少这段Java代码

时间:2016-04-29 10:01:54

标签: java performance optimization

我有一个任务,我完成了它:目标是创建一个带有2个参数的方法: 1.要计数的数字,以及2.总结果中有多少个字符/数字。

结果:假设“数字”为5,所以会计算: 01234的 5 43210 但它也会在两侧增加空间以完成第二个要求“largo”,所以如果长到15,结果将是 “01234543210”,每侧有2个空格。 所以我写了这段代码,但其他编码员告诉我他用了一半的代码。

代码中有许多假设,例如largo是>如果数字是奇数,那么拉戈也是奇数。

所以我的问题是,这段代码可以减少(重构?) [我只在我的java路径中有一个月,所以很难但是要理解XD)

public static void counter(int number, int largo) {
    int numberFull=(number*2)+1;
    int spaceFull=largo-numberFull;
    int space=spaceFull/2;
    for (int a=1;a<=space;++a)
        {System.out.print(" ");}
    for (int x=0;x<=number;x++)
        {System.out.print(x);}
    for (int y=number-1;y>=0;y--)
        {System.out.print(y);}
    for (int b=1;b<=space;++b)
        {System.out.print(" ");}
}

2 个答案:

答案 0 :(得分:1)

试试这个。

public static void counter(int number, int largo) {
    int space = (largo - (number * 2) - 1) / 2;
    String left = "0123456789".substring(0, number);
    String right = new StringBuilder(left).reverse().toString();
    String spaces = space > 0 ? String.format("%" + space + "s", "") : "";
    System.out.print(spaces + left + number + right + spaces);
}

number必须是0到9。

答案 1 :(得分:0)

我发现你的代码很好(除了格式化)。 为你的(数学)娱乐;

int spaces = largo - (2*n + 1);
print("          ".substring(0, spaces/2));
long x = pow(111111111L % pow(10, n), 2);
if (x != 0) print(0);
print(x);
if (x != 0) print(0);
print("          ".substring(0, spaces - spaces/2));
// Or: printf("%" + (spaces - spaces/2) + "s", "");

我没有发现这个解决方案“更好” - 它有更多的限制。 但它利用111 ... 111 ^ 2 == 123 .... 321。 它消除了for循环。