整數反轉
版權宣告:本文為博主原創文章,轉載請註明出處。
個人部落格地址:ofollow,noindex">https://yangyuanlin.club
歡迎來踩~~~~
- Reverse digits of an integer.
Example1:x = 123, return 321
Example2:x = -123, return -321
- 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).
-
題目大意:把一個整數的數字順序反轉,正負號不變。
-
思路:定義一個臨時變數轉存這個整數,如果是負數就變成它的相反數,然後進行迴圈,每次對10求餘取出這個整數的最後一位,然後把這個數除以10。
-
程式碼:
class Solution { public: int reverse(int x) { int temp = x > 0 ? x : (-x); int result = 0; while(temp) { result = result * 10 + temp % 10; temp /= 10; } return x > 0 ? result : (-result); } };
-
然後這樣的話是可以通過牛客網上的測試資料的,但是關鍵是它題目
Have you thought about this?
後邊的要求,大意是要考慮int
型別的溢位問題,這裡有兩種思路:
(1)定義為返回的變數為long
或者long long
型別,判斷如果大於int
max32 = 0x7fffffff;
或者小於int
min32 = 0x80000000;
就是溢位了。
(2)每次計算新的結果時,再用逆運算(把結果除以10)判斷與上一次迴圈的結果是否相同,不同就溢位。
第二種思路很巧妙,我喜歡第二種思路。
- 程式碼:
class Solution { public: int reverse(int x) { int temp = x > 0 ? x : (-x); int result = 0; while(temp) { int newResult = result * 10 + temp % 10; // 把newResult/10也就是把加上的temp%10又除掉了,如果不等於result,說明發生了溢位 if((newRessult / 10) != result) return 0; result = newRessult; temp /= 10; } return x > 0 ? result : (-result); } };
- 以上。
版權宣告:本文為博主原創文章,轉載請註明出處。
個人部落格地址:https://yangyuanlin.club
歡迎來踩~~~~