欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Leetcode 7. Reverse Integer

程序员文章站 2022-07-15 14:38:59
...

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Leetcode 7. Reverse Integer

2. Solution

  • Two loops
class Solution {
public:
    int reverse(int x) {
        if(x == 0 || x == INT_MIN) {
            return 0;
        }
        int remainder = 0;
        int y = abs(x);
        queue<int> number;
        while(y) {
            remainder = y % 10;
            number.push(remainder);
            y /= 10;
        }
        int result = 0;
        while(!number.empty()) {
            if((INT_MAX - number.front()) / 10 < result) {
                return 0;
            }
            result = result * 10 + number.front();
            number.pop();
        }
        return x == abs(x)?result:-result;
    }
};
  • One loop
class Solution {
public:
    int reverse(int x) {
        if(x == 0 || x == INT_MIN) {
            return 0;
        }
        int y = abs(x);
        int result = 0;
        int remainder = 0;
        while(y) {
            remainder = y % 10;
            if((INT_MAX - remainder) / 10 < result) {
                return 0;
            }
            result = result * 10 + remainder;
            y /= 10;
        }
        return x == abs(x)?result:-result;
    }
};

Reference

  1. https://leetcode.com/problems/reverse-integer/description/
相关标签: Leetcode

上一篇: 7. Reverse Integer

下一篇: shellcode初识