JeromeHuang

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Reverse Integer 

Reverse digits of an integer.

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

题目比较简单,注意越界和负数情况即可!

 Runtime: 16 ms

#include <stdio.h>
#include <stdlib.h>

class Solution {
public:
    int reverse(int x) {
        long long  num = 0;
        bool isPositive = true;
        if (x < 0){
            isPositive = false;
            x = -x;
        }
        while (x > 0){
            int temp = x % 10;
            num = num * 10 + temp;
            x = x / 10;
        }
        if (num > INT_MAX){
            return 0;
        }
        else{
            if (isPositive == false)
                num = num*-1;
            return num;
        }
    }
};

int main(){
    Solution solution;
    printf("%d", solution.reverse(-123));
    system("pause");
    return 0;
}

 

posted on 2015-04-20 20:32  JeromeHuang  阅读(123)  评论(0编辑  收藏  举报