C++實現(xiàn)LeetCode(7.翻轉(zhuǎn)整數(shù))
[LeetCode] 7. Reverse Integer 翻轉(zhuǎn)整數(shù)
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 store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
解法一:
class Solution { public: int reverse(int x) { int res = 0; while (x != 0) { if (abs(res) > INT_MAX / 10) return 0; res = res * 10 + x % 10; x /= 10; } return res; } };
在貼出答案的同時,OJ 還提了一個問題 To check for overflow/underflow, we could check if ret > 214748364 or ret < –214748364 before multiplying by 10. On the other hand, we do not need to check if ret == 214748364, why? (214748364 即為 INT_MAX / 10)
為什么不用 check 是否等于 214748364 呢,因為輸入的x也是一個整型數(shù),所以x的范圍也應(yīng)該在 -2147483648~2147483647 之間,那么x的第一位只能是1或者2,翻轉(zhuǎn)之后 res 的最后一位只能是1或2,所以 res 只能是 2147483641 或 2147483642 都在 int 的范圍內(nèi)。但是它們對應(yīng)的x為 1463847412 和 2463847412,后者超出了數(shù)值范圍。所以當過程中 res 等于 214748364 時, 輸入的x只能為 1463847412, 翻轉(zhuǎn)后的結(jié)果為 2147483641,都在正確的范圍內(nèi),所以不用 check。
我們也可以用 long 型變量保存計算結(jié)果,最后返回的時候判斷是否在 int 返回內(nèi),但其實題目中說了只能存整型的變量,所以這種方法就只能當個思路擴展了,參見代碼如下:
解法二:
class Solution { public: int reverse(int x) { long res = 0; while (x != 0) { res = 10 * res + x % 10; x /= 10; } return (res > INT_MAX || res < INT_MIN) ? 0 : res; } };
到此這篇關(guān)于C++實現(xiàn)LeetCode(7.翻轉(zhuǎn)整數(shù))的文章就介紹到這了,更多相關(guān)C++實現(xiàn)翻轉(zhuǎn)整數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++ Qt開發(fā)之PushButton按鈕組件的使用詳解
Qt 是一個跨平臺C++圖形界面開發(fā)庫,利用Qt可以快速開發(fā)跨平臺窗體應(yīng)用程序,本文將重點介紹QPushButton按鈕組件的常用方法及靈活運用,感興趣的小伙伴可以學習一下2023-12-12Visual C++中Tab View的多種實現(xiàn)方法
這篇文章主要介紹了Visual C++中Tab View的多種實現(xiàn)方法,包括了CTabCtrl控件、CSheetCtrl標簽選擇窗口以及靜態(tài)分割窗口等實現(xiàn)Tab View的方法,需要的朋友可以參考下2014-10-10C語言將數(shù)組中元素的數(shù)排序輸出的相關(guān)問題解決
這篇文章主要介紹了C語言將數(shù)組中元素的數(shù)排序輸出的相關(guān)問題解決,文中的題目是將元素連接起來排成一個數(shù)并要求出這類結(jié)果中數(shù)最小的一個,需要的朋友可以參考下2016-03-03