LeetCode 7 Reverse Integer(反转数字)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 7 Reverse Integer(反转数字)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目來源:https://leetcode.com/problems/reverse-integer/
?
Reverse digits of an integer.
?
Example1:?x = 123, return 321
Example2:?x = -123, return -321
解題思路:
其實這道題看起來非常簡單,要實現也是幾行代碼的事。但是有個小問題容易被忽略,就是邊界問題。什么意思呢?如果我們輸入的整數超出了int的表達范圍,這個問題要怎么解決呢? 用比int更大的數據類型存儲我們轉換后的結果,然后與int的邊界比較,超出了邊界則返回0。 Java實現: 1 public class Solution { 2 public int reverse(int x) { 3 long reverse = 0; 4 5 while(x != 0){ 6 reverse = reverse * 10 + x % 10; 7 if(reverse > Integer.MAX_VALUE || reverse < Integer.MIN_VALUE) 8 return 0; 9 x = x / 10; 10 } 11 return (int)reverse; 12 } 13 }?
?
轉載于:https://www.cnblogs.com/zpfbuaa/p/5076819.html
總結
以上是生活随笔為你收集整理的LeetCode 7 Reverse Integer(反转数字)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JS中window.showModalD
- 下一篇: ASPNET5的依赖注入