#Leetcode# 7. Reverse Integer

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

 

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

代码:

class Solution {
public:
    int reverse(int x) {
        long long ans = 0;
    int flag = 1;
    if(x < 0) {
        flag = -1;
        x = abs(x);
    }
    while(x > 0) {
        ans = ans * 10 + x % 10;
        x /= 10;
    }
    if(ans > INT_MAX) return 0;
    else if(flag < 0) return -ans;
    else return ans;
    }
};

  

posted @ 2018-11-02 21:14  丧心病狂工科女  阅读(96)  评论(0编辑  收藏  举报