标签:
Reverse digits of an integer. Returns 0 when the reversed integer overflows (signed 32-bit integer).
Given x = 123
, return 321
Given x = -123
, return -321
这题主要注意一下溢出的可能
public class Solution { /** * @param n the integer to be reversed * @return the reversed integer */ public int reverseInteger(int n) { // Write your code here long result = 0; long buf = n; boolean neg = false; if(n < 0){ neg = true; buf = -n; } while(buf > 0){ result = 10 * result + buf % 10; buf /= 10; } if(neg) result = -result; if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) return 0; return (int)result; } }
标签:
原文地址:http://www.cnblogs.com/goblinengineer/p/5246651.html