【Leetcode 7】 Reverse Integer
阿新 • • 發佈:2018-12-10
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.
問題重述:
給出一個int型的資料,進行翻轉,如果是123就翻轉成321,如果是120就翻轉成21。同樣的,負數也要進行翻轉,-120就翻轉成-21。
需要注意的問題在於有符號型的int是32位,那麼數字的範圍是 -2^31到2^31-1的範圍。比如11 2345 6789,這個不超過範圍,但是翻轉過來就一定溢位了。
解決方案:
在定義型別的時候使用long long int型,防止溢位,之後在與2^31進行比較,如果溢位就返回0,不溢位就正常返回即可。
#include<vector> #include <iostream> #include <string.h> #include <cmath> using namespace std; class Solution { public: long long int reverse(long long int x) { if (x == 0) return 0; while (1) { if (x % 10 == 0) x = x / 10; else break; } long long int m = 0; long long int temp; while (x != 0) { temp = x % 10; m = m * 10 + temp; x = x / 10; } if (abs(m) >= pow(2, 31)) return 0; else return m; } }; // 1534236469 反向就會發生溢位 // 有符號型,32位的int就相當於 -2^31 至 2^31-1(因為這邊包括了0) // 使用long long int 2^64型,即便溢位也可以在這裡進行判斷。 int main() { long long int n; cin >> n; // cout << n << endl; long long int m; Solution so; m = so.reverse(n); cout << m << endl; system("pause"); return 0; }