From leetcode

Reverse digits of an integer.

Example1:x = 123, return 321
Example2:x = -123, return -321

click to show spoilers.

Note:
The input is assumed to be a 32-bit signed integer. Your function shouldreturn 0 when the reversed integer overflows.

Solution:

  1. Classic reverse integer problem. Using rolling of an integer: y * 10 + digit
  2. Importance case: how to handle integer overflow. If you are still in the integer realm then there is no way you can check since once it overflows it already becomes another number. So you use long to store or convert to double to do the calculation.
  3. Probably can use bit manipulation, I don't know how to do it now.

class Solution {

public:

int reverse\(int x\) {

    bool neg = false;

    if \(x < 0\) {

        x = -x;

        neg = true;

    }



    long y = 0;

    while \(x > 0\) {

        int temp = x % 10;

        if \(y \* 10 + temp > INT\_MAX\) {

            y = 0; break;

        }



        y = y \* 10 + temp;

        x = x / 10;

    }



    if \(neg == true\) y = -y;

    return y;

}

};

results matching ""

    No results matching ""