Utopi
a

整数反转

又是一次失败的Debug型编程呢_(:з」∠)_

Given a 32-bit signed integer, reverse digits of an integer.

Example

Input: 123 Output: 321
Input: -123 Output: -321
Input: 120 Output: 21

Note:

Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

我的( 3 ms )

public int reverse(int x) { if (x > 2147483647||x <= -2147483648){ return 0;//防止输入溢出 } int y =Math.abs(x);//防止负数 String str = String.valueOf(y); int [] tmp = new int[str.length()]; for(int i=0;i<str.length();i++){ tmp[i] = Integer.parseInt(String.valueOf(str.charAt(i))); } long sum=0;//防止输出溢出 for(int j=tmp.length-1;j>=0;j--){ sum=sum*10+tmp[j]; } if (x<0){ sum= 0-sum ;//恢复负数 } if (sum > 2147483647||sum < -2147483648){ return 0;//防止输出溢出 } return (int)sum; }

先把数字转换成数组,然后再把数组转换回数字,中间处理好负数和溢出的问题。

1 ms

class Solution { public int reverse(int x) { int rev = 0; while(x != 0){ int pop = x % 10; x = x / 10; if(rev > Integer.MAX_VALUE / 10 || (rev == Integer.MAX_VALUE / 10 && pop > Integer.MAX_VALUE % 10)){ rev = 0; break; }else if(rev < Integer.MIN_VALUE / 10 || (rev == Integer.MIN_VALUE / 10 && x < Integer.MIN_VALUE % 10)){ rev = 0; break; } rev = rev * 10 + pop; } return rev; } }

2 ms (谁都不服就服你!)

class Solution { public int reverse(int x) { long n = 0; while(x!=0){ n = n*10 + x%10; x/=10; } return (int)n==n? (int)n:0;//牛逼!! } }