码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode[7]-Reverse Integer

时间:2015-06-12 23:55:44      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:末尾   数字逆转   integer   c++   leetcode   

Reverse digits of an integer.

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


取一个数的最后一位,用x % 10,取一个数的前n-1位(共n位),用x/10,每一次取的时候,都将上一次取的数乘以10,然后再加上末尾的数即可,代码如下:

Code(C++)

class Solution {
public:
    int reverse(int x) {
        long result = 0;
        while(x != 0)
        {
            result = result*10 + x % 10;
            x /= 10;
        }
        return (result > INT_MAX || result < INT_MIN)? 0 : result;
    }

};

Leetcode[7]-Reverse Integer

标签:末尾   数字逆转   integer   c++   leetcode   

原文地址:http://blog.csdn.net/dream_angel_z/article/details/46476481

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!