gpt4 book ai didi

java - 如何在不形成回文的情况下反转数字

转载 作者:行者123 更新时间:2023-11-30 10:52:05 26 4
gpt4 key购买 nike

我正在尝试解决一个挑战。这是我能够做到的,但我还不能获得 100% 的工作代码

我做错了什么吗?

问题:

The problem is as follows: choose a number, reverse its digits and add it to the original. If the sum is not a palindrome (which means, it is not the same number from left to right and right to left), repeat this procedure.

import java.io.*;
public class Reverse_and_add {

public static void main (String[] args) throws IOException {
File file = new File("addition.txt");
BufferedReader buffer = new BufferedReader(new FileReader(file));
String line;
while ((line = buffer.readLine()) != null) {
line = line.trim();
String[] addition = line.split(" ");
int[] myAddition = new int[addition.length];
int convert = 0;
for (int i = 0; i < myAddition.length; i++) {
myAddition[i] = Integer.parseInt(addition[i]);
convert = myAddition[i];
}
int result=0;
int count =0;
result = convert + reverse(convert);
do {
result = result + reverse(result);
System.out.println(count+" "+result);
count++;
} while (result != reverse(result));


}
}

public static int reverse(int n){
int reverse = 0;
while( n != 0 )
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
return reverse;
}

}

最佳答案

要完成这个问题,你必须把它分解。分三部分,取反,判断是否回文,加完为止。我几乎分解了这个问题,然后在下面的代码中实现了它。请注意:isPalindrome()reverseInt() 方法的实现取自其他 SO 线程。 无论您如何实现,获取问题的值(value)取决于您。

public class Main {

public static void main(String[] args) {
// TODO Auto-generated method stub
int num = 54; //THis can be whatever you want
while(!isPalindrome(Integer.toString(num))){
int n = reverseInt(num);
num +=n;
}
System.out.println(num);
}
//Checks if a number is a string is a palindrome
public static boolean isPalindrome(String str) {
return str.equals(new StringBuilder(str).reverse().toString());
}

//Takes an int, reverses it
public static int reverseInt(int input)
{
long reversedNum = 0;

long input_long = input;

while (input_long != 0)
{
reversedNum = reversedNum * 10 + input_long % 10;
input_long = input_long / 10;
}

if (reversedNum > Integer.MAX_VALUE || reversedNum < Integer.MIN_VALUE)
{
throw new IllegalArgumentException();
}
return (int)reversedNum;
}
}

关于java - 如何在不形成回文的情况下反转数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34505272/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com