Java-使用字符串操作翻转整数有时会返回错误

Java-使用字符串操作翻转整数有时会返回错误,java,string,Java,String,这是较长编码挑战的一部分-其中一部分涉及“翻转”输入编号的数字(即1234变为4321)并删除前导零(如适用) 下面,我编写了实现这一点的方法flipOpp。大多数情况下,它工作得非常完美。但有时,我会得到一个错误,因为最后一个数字变成了破折号(“-”),很明显,如果其中一个数字是破折号,Integer.parseInt()方法将不起作用 你知道这是什么原因吗?还有,有没有更简单的方法来翻转整数的数字?我现在使用的方法似乎不是很有效-将int转换为字符串,然后转换为字符数组,操作此数组的字符,将

这是较长编码挑战的一部分-其中一部分涉及“翻转”输入编号的数字(即1234变为4321)并删除前导零(如适用)

下面,我编写了实现这一点的方法flipOpp。大多数情况下,它工作得非常完美。但有时,我会得到一个错误,因为最后一个数字变成了破折号(“-”),很明显,如果其中一个数字是破折号,Integer.parseInt()方法将不起作用


你知道这是什么原因吗?还有,有没有更简单的方法来翻转整数的数字?我现在使用的方法似乎不是很有效-将int转换为字符串,然后转换为字符数组,操作此数组的字符,将其转换回字符串,最后转换回int

谢谢!此方法的代码如下所示:

// third operation: reverse the digits and remove leading zeros
    public static int flipOpp(int num){
        char temp;
        // change int to a String
        String stringNum = Integer.toString(num);
        // change String to a char array of digits
        char[] charNum = stringNum.toCharArray();
        // flip each character and store using a char temp variable
        for (int i=0;i<charNum.length/2;i++){
            temp = charNum[i];
            charNum[i]=charNum[charNum.length-i-1];
            charNum[charNum.length-i-1]=temp;
        }
        // turn flipped char array back to String, then to an int
        // this process removes leading zeros by default
        String flipString = new String(charNum);
        if (flipString.length()<7){
            int flipInt = Integer.parseInt(flipString);
            return flipInt;
        }
        else return 0;

    }
//第三个操作:反转数字并删除前导零
公共静态int flipOpp(int num){
焦炭温度;
//将int更改为字符串
字符串stringNum=Integer.toString(num);
//将字符串更改为数字字符数组
char[]charNum=stringNum.toCharArray();
//翻转每个字符并使用char temp变量存储
对于(int i=0;i

你知道这是什么原因吗

听起来肯定是负数

有没有更简单的方法来翻转整数的数字?我现在使用的方法似乎不是很有效

保持它为整数,不要担心它的负数

public static int flipOpp(int num) {
    int reversed = 0;

    while (num!=0) {
        reversed = reversed*10 + num%10; 
        num /= 10;   
    } 
    return reversed;
} 
例如,-50

0*10+0=0
-50/10=-5
- - 
0*10+(-5)=-5
-5/10=0
- - 
END, output -5

反转字符串是这样描述的。“知道是什么导致的吗?”这是什么?是的。负数导致了这一点。你真的不应该使用字符串。如果
num
大于
999999
,代码真的应该返回
0