LeetCode 算法习题 第三周

Reverse Integer

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

题目大意

将一个整数进行位数调换,使得最高位成为个位,次高位成为十位,……
比如123 变成321

我的解答

class Solution {
public:
    int reverse(int x) {
        int ans = 0;
        while (x) {
            int temp = ans * 10 + x % 10;
            if (temp / 10 != ans)
                return 0;
            ans = temp;
            x /= 10;
        }
        return ans;
    }
};

你可能感兴趣的:(LeetCode 算法习题 第三周)