[leet code] Reverse Integer
2014-01-01 09:03
316 查看
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
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. 利用求余%逐次获得int变量中的每一位
2. 判断是否为负数
3. int长度为32位 从-2的31次方到2的31次方
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
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).
public class Solution { public int reverse(int x) { boolean neg = false; if (x < 0) { neg = true; x = -x; } int y = 0; while (x>0){ y = y*10 + x%10; x = x/10; } return neg?-y:y; } }
思路总结:
1. 利用求余%逐次获得int变量中的每一位
2. 判断是否为负数
3. int长度为32位 从-2的31次方到2的31次方
相关文章推荐
- Leet code---Reverse Integer
- Leet Code 7 Reverse Integer
- Leet Code Medium 18 4Sum
- [leet code] Best Time to Buy and Sell Stock
- [leet code] Linked List Cycle II
- leet code. 15. 3Sum (暴力???)
- [leet code] Search a 2D Matrix
- [leet code] Spiral Matrix II
- [leet code] Unique Paths II
- leet code2 Add Two Numbers
- leet code 004:Median of Two Sorted Arrays
- [leet code 4] Median of Two Sorted Arrays
- [leet code 135]candy
- Leet Code 20 Valid Parentheses - 有效括号 - Java
- 【Leet Code】80. Remove Duplicates from Sorted Array II---Medium
- 【Leet Code】283. Move Zeroes---Easy
- Leet Code 52 N-Queens II - N皇后问题 - Java
- Leet Code 58 Length of Last Word - 最后一个单词的长度 -Java
- 【Leet Code】Add Two Numbers
- Leet Code 19 Remove Nth Node From End of List