在过去的几个星期里,我一直在做谷歌Foobar的挑战,我一直进展得很好。我现在是第三层的1/3。然而,在过去的几周里,有很多次我觉得我的代码可以更好一些。所以今天我偶然发现了这个社区,我认为请你们检查我的代码是个好主意。
这就是我奉命做的事:
燃料控制机制有三项运作:
编写一个名为answer(n)的函数,该函数以一个正整数作为字符串,并返回将球团数转换为1所需的最小操作数。燃油进气控制面板只能显示高达309位长的数字,因此不会有比用这么多位数表示的球团数更多的球团。
这是我的解决办法:
public static int answer(String n) {
//convert n to BigInteger
BigInteger x = new BigInteger(n);
BigInteger two = new BigInteger("2");
BigInteger three = new BigInteger("3");
BigInteger y, z;
int counter = 0;
//Loop for as long as x is not equal to 1
while(!x.equals(BigInteger.ONE)){
//Check if x is divisible by 2
if(x.mod(two).equals(BigInteger.ZERO)){
//divide x by 2
x = x.divide(two);
} else {
//subtract x by 1 and then divide by 2 store in variable z
y = x.subtract(BigInteger.ONE);
z = y.divide(two);
//check if the result of that leaves a number that's divisible by 2, or check if x is equal to 3
if(z.mod(two).equals(BigInteger.ZERO) || x.equals(three)){
x = y;
} else {
x = x.add(BigInteger.ONE);
}
}
counter++;
}
return counter;
}对于这一挑战,与以前的挑战相比,我对代码的简洁性更加自信和满意。但鉴于我仍然是个新手,这是我第一次使用BigInteger,我非常想看一看。
发布于 2018-08-07 22:41:44
您可以在BigInteger中使用按位方法。
您可以同时去掉.mod(2)和BigInteger 2,而使用!__.testBit(0)。
返回true当且仅当指定位被设置时。(计算
((this & (1<<n)) != 0).)
您也可以使用.shiftRight(1)除以2
返回值为BigInteger的
(this >> n)。执行符号扩展。移位距离n可以是负的,在这种情况下,这种方法执行左移位。(计算floor(this / 2n).)
我没有花很多心思,但我认为您也可以找到一个聪明的方法,用testBit和bitLength来摆脱3,但我认为. .compareTo/equals方法是可以的。
public static int answer(String n) {
//convert n to BigInteger
BigInteger x = new BigInteger(n);
BigInteger three = new BigInteger("3");
BigInteger y, z;
int counter = 0;
//Loop for as long as x is not equal to 1
while(!x.equals(BigInteger.ONE)){
//Check if x is divisible by 2
if(!x.testBit(0)){
//divide x by 2
x = x.shiftRight(1);
} else {
//subtract x by 1 and then divide by 2 store in variable z
y = x.subtract(BigInteger.ONE);
z = y.shiftRight(1);
//check if the result of that leaves a number that's divisible by 2, or check if x is equal to 3
if(!z.testBit(0) || x.equals(three)){
x = y;
} else {
x = x.add(BigInteger.ONE);
}
}
counter++;
}
return counter;
}https://codereview.stackexchange.com/questions/201165
复制相似问题