这是我要解决的问题。给定一个像6928这样的数字:
difference between 6 and 9 is 3
difference between 9 and 2 is 7
difference between 2 and 8 is 6
因此,简化形式为376。由于这不是两位数,所以我们重复此过程:
difference between 3 and 7 is 4
difference between 7 and 6 is 1
结果是41,这是一个两位数,然后是解决方案!
这是使用递归方法的尝试,但我希望以非递归的方式进行:
public static int twodigit(int value) {
while (value > 99)
value = reduce(value);
return value;
}
private static int reduce(int value) {
return (value<=9? 0:reduce(value/10)*10 + Math.abs(value/10%10-value%10));
}
答案 0 :(得分:5)
您可以使用几个嵌套循环和一些数学运算来添加和选择数字。
public static void main(String[] args) {
System.out.println(reduce(6928));
}
public static long reduce(long v) {
while(v > 9) {
System.out.println(v);
long y = 0, factor = 1;
// go through each digit from the bottom and calc the diff.
while(v > 9) {
y += factor * Math.abs(v % 10 - v / 10 % 10);
v /= 10;
// each digit is worth 10x the last.
factor *= 10;
}
v = y;
}
return v;
}
打印
6928
376
41
3
答案 1 :(得分:1)
一种更简单的迭代方法是将数字转换为字符串并将其传递给以下方法
private static String calculateTwoDigitNumber(String number) {
while (number.length() > 2) {
String tmpNumber = "";
for (int i = 1; i < number.length(); i++) {
tmpNumber += Math
.abs(Integer.parseInt(number.charAt(i - 1) + "") - Integer.parseInt(number.charAt(i) + ""));
}
number = tmpNumber;
}
return number;
}
如果输入字符串很大,则可以使用StringBuilder代替String