Reverse Integer

Reverse Integer

Reverse digits of an integer.

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

 

比较简单,以下是步骤:

1. 计算x的长度,就是有几位;

2. 从低位开始,取余得到这一位的数字,然后乘以10^(len-i),再加到结果的数字上;

上代码:

class Solution {
public:
    int reverse(int x) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int len = getLen(x);
        int rst = 0;
        for (int i = 1; i <= len; i++)
        {
            int t = x % 10;
            x = x / 10;
            int a = len - i, temp = 1;
            while (a > 0)
            {
                temp = temp * 10;
                a--;
            }
            rst += t * temp;
        }
        return rst;
    }
    int getLen(int x)
    {
        int len = 0, t = x;
        while (t)
        {
            t = t / 10;
            len += 1;
        }
        return len;
    }
};

 

posted on 2013-07-22 23:23  赵乐ACM 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/dollarzhaole/p/3207695.html

你可能感兴趣的:(Reverse Integer)