Reverse digits of an integer.

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

解题:设定一个变量sum存放反转后的答案,每次取输入x的最后一位n,并用sum = sum*10+n更新sum。

例如题设的数字123,初始sum为0,过程如下:

取末尾的3,sum=3,x=12

取末尾的2,sum=32,x=1

取末尾的1,sum=321,x=0

特别注意x一开始就是0的处理,直接返回0就可以了。

代码:

 class Solution {
public:
int reverse(int x) {
int sum = ;
if(x == )
return ;
while(x != ){
int temp = x%;
sum = sum*+temp;
x /= ;
}
return sum;
}
};

题目还给出了一些思考:

1.If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

上述的方法避免了这个问题,10和100的输出都是1

2.Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases? Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

最新文章

  1. 【iOS】Jenkins Gitlab持续集成打包平台搭建
  2. 关于Android多项目依赖在Eclipse中无法关联源代码的问题解决
  3. bootstrap框架----像素
  4. 转:HTML5标准与性能之四:asm.js
  5. yum change source repo centos共存安装sun jdk6和jdk7
  6. C#操作office进行Excel图表创建,保存本地,word获取
  7. [转]使用 PIVOT 和 UNPIVOT
  8. 剑指offer_面试题11 数值的整数次方_考察代码的完整性
  9. 黑马程序猿——Java中的类载入器
  10. 关于SD卡
  11. mysql数据文件迁移到新的硬盘分区的方法
  12. Java代码之输出参数和(强制类型转换)
  13. cocos2dx - 环境配置,项目创建
  14. b2OJ_1565_[NOI2009]植物大战僵尸_拓扑排序+最大权闭合子图
  15. vue前端面试题知识点整理
  16. 缓存:前端页面缓存、服务器缓存(依赖SQL)MVC3
  17. vue-cli项目开发/生产环境代理实现跨域请求+webpack配置开发/生产环境的接口地址
  18. [leetcode]53. Maximum Subarray最大子数组和
  19. android 三种定时器的写法
  20. Bitlocker驱动器加密使用

热门文章

  1. VBA 按列查找小工具类似lookUp函数
  2. android电话状态的监听
  3. Babel中的stage-0,stage-1,stage-2以及stage-3
  4. jquery validate 详解
  5. 【Selenium + Python】之OSError: [WinError 6] 句柄无效。
  6. 03 Memcached内存分布机制
  7. Linux5_环境变量
  8. 第三方-Swift2.0后Alamofire的使用方法
  9. Cassandra数据库Java訪问
  10. VC++ 读写注冊表,注冊文件图标关联