7.Reverse Integer題目和答案詳解
阿新 • • 發佈:2018-12-27
1 題目簡述
Given a 32-bit signed integer, reverse digits of an integer.
給定一個32位有符號整數,反轉這個整型數。
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.2 答案詳解
(1) 解決思想
本次解答採用C++編寫,C++相對於C語言的一個重要的特點是:面向物件程式設計(OOP),故我們採用類的方法來實現所述要求。要處理的是32位有符號整數,即int型整數,對於不同系統和編譯器的int型別是不是佔4個位元組,讀者可以自己用sizeof()函式確認,只要找到佔4個位元組的整型即可,在這不做過多討論。 首先,要知道佔4個位元組的有符號整型(以後將用int代替)的十進位制範圍為:-2147483648~2147483647,在標頭檔案climits中對其最大值和最小值進行了巨集定義:INT_MAX和INT_MIN。若給定整型數的反轉數超出了這個範圍,將返回結果0。(2) 設計程式
所設計的程式採用類模板,這樣可以對程式碼進行重用,從而對各種整數進行反轉時無需做過多的程式改動,程式如下:#include <iostream>
#include <climits>
#include <iterator>
#include <vector>
#include <cmath>
using std::vector;
using std::iterator;
using std::cout;
using std::endl;
template<class T>
class ReverseInteger
{
private:
T num_;
public:
ReverseInteger(const T& num = 0):num_(num) {}
T result();
};
template<class T>
T ReverseInteger<T>::result()
{
vector<T> nums;
T num(num_);
T res(0);
T divisor(10);
int sign(1);
typename vector<T>::iterator ith;
typename vector<T>::iterator itt;
if(num == INT_MIN ) {
return res;
} else if(num < -9) {
sign = -1;
num = -num;
} else if(num < 10) {
return res = num;
}
while(num % divisor or num / divisor) {
nums.push_back(num % divisor);
num /= divisor;
}
ith = nums.begin();
itt = nums.end()-1;
long judge(0);
long max(INT_MAX);
long min(INT_MIN);
int n;
do {
n = distance(nums.begin(),itt);
judge += (*ith) * pow(10,n);
judge = judge * sign;
if(judge > max or judge < min) {
return res = 0;
}
judge = judge * sign;
ith++;
itt--;
} while(itt != nums.begin()-1);
return res = judge * sign;
}
int main()
{
int data = -123456789;
int res;
ReverseInteger<int> ri(data);
res = ri.result();
cout << "integer number:" << data << endl;
cout << "res:" << res << endl;
}
程式執行結果為:integer number: -123456789 res: -987654321