7. Reverse Integer (Easy)

https://leetcode.com/problems/reverse-integer/

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

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

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.

Hints

Solutions

  • Java
class Solution {
    long min = -1l << 31; // never use int, otherwise overflow happens
    long max = 1l << 32-1;
    public int reverse(int x) {
        long result = 0;
        long xx = x;
        while(xx != 0) {
            long m = xx % 10;

            xx = xx / 10;

            if (x > 0 && result * 10 + m > max) return 0;
            if (x < 0 && result * 10 + m < min) return 0;

            result = result * 10 + m;
        }

        return (int)result;
    }
}
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-04-04 11:33:32

results matching ""

    No results matching ""