LeetCode:7. Reverse Integer

来源:互联网 发布:百马百担c语言编程答案 编辑:程序博客网 时间:2024/06/05 01:58

代码如下:

classSolution{public:

intreverse(int x) {

int ans = 0;

while (x) {

int temp = ans * 10 + x % 10;

if (temp / 10 != ans)

return0;

ans = temp;

x /=10;

}

return ans; }};


思路如下:

(1)设置一个temp,初始等于X,当temp/10等于temp的时候,说明已经进行到了最后一位,停止;

(2)temp/10不等于temp时,设置一个ans,用于储存当前temp余10的数字。

(3)temp = temp/10,若temp/10还是不等于temp,将ans*10达到进一位的作用,然后再加上当前temp余10的数字,然后重复第三步直到满足第一步的条件为止。

0 0
原创粉丝点击