首页 > 其他 > 详细

Reverse Integer

时间:2018-09-27 01:03:43      阅读:190      评论:0      收藏:0      [点我收藏+]

Description:

Given a 32-bit signed integer, reverse digits of an integer.

Note:

Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [?231,  231 ? 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Solution:

 1 int reverse(int x)
 2 {
 3     int ans = 0;
 4     int tmp = 0;
 5     while (x) {
 6         tmp = ans * 10 + x % 10;
 7         if (tmp / 10 != ans) {
 8             return 0;
 9         }
10         ans = tmp;
11         x /= 10;
12     }
13     return ans;
14 }

tmp = ans * 10 + x % 10 = ans * 10 + (x - x / 10 * 10)

tmp / 10 = ans + x / 10  - x / 10 = ans

if integer tmp doesn‘t overflow.

 

Reverse Integer

原文:https://www.cnblogs.com/ouch/p/9710919.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!