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

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

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


题目标签:Math

  题目给了我们一个int 数字,让我们倒转它。
  利用 % 10 来拿到最右边数字,然后每次把res * 10 加上新拿到的数字,利用 x / 10 来遍历剩下的数字。
  这一题关键在于,如何检查 overflow,可以利用long,但是如果题目给你的是long,那你如何检查long 是否overflow呢。所以要在不使用更大的type的情况下来检查。
 
  新的res 是如何产生的:
    newRes = res * 10 + x % 10;
  那么如果新的res 没有overflow 的话,把newRes 倒推回去应该是和旧的 res 相等的:
    (newRes - x % 10) / 10 == res
  利用这一点,如果overflow的话,那么倒退回去肯定是 不相等的。
 
 
 
 

Java Solution:

Runtime beats 80.84%

完成日期:06/12/2017

关键词:reverse int

关键点:% 10; / 10

 class Solution
{
public int reverse(int x)
{
int res = 0; while(x != 0)
{
int tail = x % 10;
int newRes = res * 10 + tail; if((newRes - tail) / 10 != res) // check overflow
return 0; res = newRes;
x = x / 10;
} return res;
}
}

参考资料:https://discuss.leetcode.com/topic/6104/my-accepted-15-lines-of-code-for-java

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

最新文章

  1. js中用正则表达式 过滤特殊字符 ,校验所有输入域是否含有特殊符号
  2. NOIp 0910 爆零记
  3. 哈希表--HashSet<T>
  4. python实现字体闪图
  5. cocos2d-x如何优化内存的应用
  6. CSS3 旋转的八卦图
  7. wiki oi3117 高精度练习之乘法
  8. Eclipse 打JAR包,插件FatJar 安装与使用
  9. [算法] avl树实现
  10. Docker for Mac与IntelliJ Docker Integration插件的兼容性问题
  11. python学习之re (?P...)通过关键字获取组以及( P=name)
  12. Oracle单机Rman笔记[5]---脱机异地还原
  13. 常用浏览器内核!IE,Chrome ,Firefox,Safari,Opera 等内核
  14. zabbix3.4.7Web页面监控
  15. 使用TopShelf做windows服务安装 ---安装参数解释
  16. HBase学习之路 (十)HBase表的设计原则
  17. PHP学习心得2
  18. Python数据类型-02.字符串
  19. 【TP3.2与TP5.0区别】
  20. jQuery语法、选择器、效果等使用

热门文章

  1. 【转】jvm类加载
  2. 一个完整的网站记录(springmvc hibernate juery bootstrap)
  3. 后台接收不到postman发送的xml参数的解决办法
  4. 数据库–Cobar分布式数据库集群MySQL中间件
  5. C# HttpWebRequest Post Get 请求数据
  6. vuex状态管理demo
  7. java面试题链接
  8. Word 格式优化
  9. ConcurrentHashMap笔记
  10. FileReader实现读取文件内容并输出到屏幕上