您的位置:首页 > 其它

【leetcode】Reverse Integer

2014-08-14 21:01 363 查看
题目:

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

Example2: x = -123, return -321
click to show spoilers.

解析:将一个整形数字倒序输出,注意判断正负。这道题在华为面试的时候遇到过,很简单。

class Solution {
public:
    int reverse(int x) {
        int result = 0;
        bool ifNegative = false;
        if(x<0){
            ifNegative = true;
            x = -x;
        }
        while(x!=0){
            int temp = x % 10;
            result = result * 10 + temp;
            x = x/10;
        }
        if(ifNegative){
            result = -result;
        }
        return result;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: