LeetCode 7. Reverse Integer
2017-06-12 21:43
190 查看
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
题目要求很简单,对整数进行反转。需要注意的一点是,当超出了整型的范围,即INT_MIN~INT_MAX之间的话,需要返回0。但是y不能直接和INT_MIN以及INT_MAX进行比较。因此需要在对y赋值前与INT_MAX/10以及INT_MIN/10进行比较,如果超出范围则返回10。代码实现如下:
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
题目要求很简单,对整数进行反转。需要注意的一点是,当超出了整型的范围,即INT_MIN~INT_MAX之间的话,需要返回0。但是y不能直接和INT_MIN以及INT_MAX进行比较。因此需要在对y赋值前与INT_MAX/10以及INT_MIN/10进行比较,如果超出范围则返回10。代码实现如下:
class Solution { public: int reverse(int x) { int y = 0; while(x != 0){ if(y > INT_MAX/10 || y < INT_MIN/10) return 0; y = y*10+x%10; x = x/10; } return y; } };
相关文章推荐
- LeetCode 43: First Missing Positive
- [LeetCode]Linked List Cycle II
- Permutations——LeetCode
- 【LeetCode】Palindrome Number
- [leetcode] 4Sum
- leetcode[95] Unique Binary Search Trees II
- Leetcode: Binary Search Tree Iterator
- 【leetcode】Best Time to Buy and Sell Stock
- LeetCode Implement Trie (Prefix Tree)
- LeetCode——Word Break
- leetcode3:Longest Substring Without Repeating Characters
- 【LeetCode】Binary Tree Level Order Traversal 解题报告
- leetcode Implement Stack using Queues
- LeetCode数据库练习题MySql
- LeetCode Binary Tree Vertical Order Traversal
- [LeetCode82]Remove Duplicates from Sorted List II
- [Leetcode]66. Plus One
- Leetcode 387. First Unique Character in a String 第一个唯一字符 解题报告
- LeetCode 67 - Add Binary
- Leetcode: Minimum Unique Word Abbreviation