[Lintcode] #413 反转整数

来源:互联网 发布:百万淘宝客程序 编辑:程序博客网 时间:2024/05/24 03:24

将一个整数中的数字进行颠倒,当颠倒后的整数溢出时,返回 0 (标记为 32 位整数)。


样例

给定 x = 123,返回 321

给定 x = -123,返回 -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 re = 0;int flag = n > 0 ? 1 : -1;n = Math.abs(n);while (n > 0) {int cur = n % 10;n /= 10;re = re * 10 + cur;}if (re > Integer.MAX_VALUE)return 0;elsereturn (int) re * flag;    }}


原创粉丝点击