顛倒整數 c++演算法 leetcode7
阿新 • • 發佈:2018-11-05
題目:顛倒整數
給定一個 32 位有符號整數,將整數中的數字進行反轉。
示例 1:
輸入: 123
輸出: 321
示例 2:
輸入: -123
輸出: -321
示例 3:
輸入: 120
輸出: 21
注意:
假設我們的環境只能儲存 32 位有符號整數,其數值範圍是 [−231, 231 − 1]。根據這個假設,如果反轉後的整出,則返回 0。
解答:
①翻轉數字問題需要注意的就是溢位問題。
為什麼會存在溢位問題呢,我們知道int型的數值範圍是 -2147483648~2147483647, 那麼如果我們要翻轉 1000000009 這個在範圍內的數得到 9000000001,而翻轉後的數就超過範圍。用long long 型資料,數值範圍-9223372036854775808~9223372036854775807, 遠大於int型這樣就不會出現溢位問題。
②解題思路
先判斷是否為負數,為負數乘以-1,當為正數時直接進入迴圈,然後判斷是否超限返回0值。再判斷標誌變數,添加回正負號。
程式碼示例:
1.類的封裝
class Solution { public: int reverse(int x) { long long res = 0; bool isPosition = true; if (x < 0) { isPosition = false; x *= -1; } while (x > 0) { res = res * 10 + x % 10; x /= 10; } if (res > INT_MAX) return 0; if (isPosition) return res; else return -res; } };
2.標頭檔案
#include<iostream>
#include<vector>
using namespace std;
3.z主函式
int main()
{
int a = 0.7;
cout << a << endl;
int b = 321;
class Solution pt;
int c = pt.reverse(b);
cout << c << endl;
}
寫的程式碼都在VS2015下測試沒有問題,如果輸入為int b = 321;
輸出為
補充
int a = 0.7;
cout << a << endl;
當數值型別為int,取值小於1時。其值直接為0,保證class Solution裡面while()跳出迴圈。
該題所有測試程式碼如下
#include<iostream>
#include<vector>
using namespace std;
class Solution
{
public:
int reverse(int x)
{
long long res = 0;
bool isPosition = true;
if (x < 0)
{
isPosition = false;
x *= -1;
}
while (x > 0)
{
res = res * 10 + x % 10;
x /= 10;
}
if (res > INT_MAX)
return 0;
if (isPosition)
return res;
else
return -res;
}
};
int main()
{
int a = 0.7;
cout << a << endl;
int b = 321;
class Solution pt;
int c = pt.reverse(b);
cout << c << endl;
}