LeetCode No.7 Reverse Integer |

2016-11-02  本文已影响0人  wxqyppqm

Q:

Reverse digits of an integer.
Example1: x = 123, return 321Example2: x = -123, return -321

  • If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

A:

public class Solution {
    public int reverse(int x) {
        long result =0;     //为了处理Integer的边界值,这里初始化成long
        while(x != 0)
        {   //之前的结果乘以10(在前,前一位),后来的值是module 10求模得到的(在后,后一位)
            result = (result*10) + (x%10); 
            if(result > Integer.MAX_VALUE) return 0;
            if(result < Integer.MIN_VALUE) return 0;
            x = x/10;       //处理下一位,从右至左
        }
        return (int)result; 
    }
}

test case: 939

test case: -100


Notes:

关于module取模

(-10)/3 = -3
10/(-3) = -3
(-10)/(-3) = 3

(-10)%3 = -1
10%(-3) = 1
(-10)%(-3) = -1

5%3 = 2
-5%3 = -2
5%-3 = 2
-5%-3 = -2 //结果符号由之前的那个数字来决定
5.3%3 = 2.3
5%3.3 = 1.7000000000000002 //取模支持小数
5.3%3.3 = 2.0 //两个小数也可以取模

上一篇下一篇

猜你喜欢

热点阅读