LeetCode题库解答与分析——#7.颠倒整数ReverseInteger
2018-03-14 21:23
483 查看
#7 颠倒整数 Reverse Integer
给定一个范围为 32 位 int 的整数,将其颠倒。Given a 32-bit signed integer, reverse digits of an integer.
例 1:输入: 123
输出: 321
例 2:输入: -123
输出: -321
例 3:输入: 120
输出: 21
注意:假设我们的环境只能处理 32 位 int 范围内的整数。根据这个假设,如果颠倒后的结果超过这个范围,则返回 0。
个人思路:
每次循环取出末位并加上上次循环结果的10倍
代码(Java):class Solution {
public int reverse(int x) {
long result=0;
long X=x;
while(X!=0){
result = result * 10 + X % 10;
X = X / 10;
}
if (result < Integer.MIN_VALUE || result > Integer.MAX_VALUE) {
result = 0;
}
return (int)result;
}
}
给定一个范围为 32 位 int 的整数,将其颠倒。Given a 32-bit signed integer, reverse digits of an integer.
例 1:输入: 123
输出: 321
例 2:输入: -123
输出: -321
例 3:输入: 120
输出: 21
注意:假设我们的环境只能处理 32 位 int 范围内的整数。根据这个假设,如果颠倒后的结果超过这个范围,则返回 0。
个人思路:
每次循环取出末位并加上上次循环结果的10倍
代码(Java):class Solution {
public int reverse(int x) {
long result=0;
long X=x;
while(X!=0){
result = result * 10 + X % 10;
X = X / 10;
}
if (result < Integer.MIN_VALUE || result > Integer.MAX_VALUE) {
result = 0;
}
return (int)result;
}
}
相关文章推荐
- LeetCode题库解答与分析——#12.整数转罗马数字IntegerToRoman
- LeetCode题库解答与分析——#3.无重复字符的最长子串LongestSubstringWithoutRepeatingCharacters
- LeetCode题库解答与分析——#5.最长回文子串LongestPalindromicSubstring
- LeetCode题库解答与分析——#53.最大子序和MaximumSubarray
- LeetCode题库解答与分析——#1.两数之和TwoSum
- LeetCode题库解答与分析——#91. 解码方法DecodeWays
- LeetCode题库解答与分析——#152. 乘积最大子序列MaximumProductSubarray
- LeetCode题库解答与分析——#62. 不同路径UniquePaths
- LeetCode题库解答与分析——#95. 不同的二叉查找树 IIUniqueBinarySearchTreeII
- LeetCode题库解答与分析——#2.两数相加AddTwoNumbers
- LeetCode题库解答与分析——#63.不同路径IIUniquePathsII
- LeetCode题库解答与分析——#96. 不同的二叉查找树UniqueBinarySearchTree
- LeetCode题库解答与分析——#70. 爬楼梯ClimbingStairs
- LeetCode题库解答与分析——#120. 三角形最小路径和Triangle
- LeetCode题库解答与分析——#121. 买卖股票的最佳时机BestTimeToBuyAndSellStock
- LeetCode题库解答与分析——#9.回文数PalindromeNumber
- leetcode 10: Regular Expression Matching 分析及解答
- leetcode Online Judge 150题 解答分析之一 Reverse Words in a String
- 【LeetCode题意分析&解答】38. Count and Say
- 【LeetCode题意分析&解答】41. First Missing Positive