Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Have you thoughtabout this?
Here are some good questions to ask before coding. Bonus points for you ifyou have already thought through this!
If the integer‘s last digit is 0, what should the output be? ie, casessuch as 10, 100.
Did you notice that the reversed integer might overflow? Assume the inputis a 32-bit integer, then the reverse of 1000000003 overflows. How should youhandle such cases?
For the purpose of this problem, assume that your function returns 0 whenthe reversed integer overflows.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
HideTags
#pragma once #include<iostream> #include<queue> using namespace std; //long 固定为32位 int 在32位机器上是32位,long long 固定是64位 int reverse(int x) { long long val = abs(x);//绝对值 long long result = 0; long long up = 2147483647; long long down = 2147483648; down = -down;//2147483648计算机认为是unsigned int 不能加负号,曲线救国 int flag = 1;//符号 if (x < 0) flag = -1; queue<int> q; int temp = 0; while (val > 0) { temp = val % 10;//取余 q.push(temp); val /=10; } while (!q.empty()) { result =result*10 + q.front(); q.pop(); } if (result > up || result < down) return 0; return flag*result; } void main() { cout << reverse(1000000003) << endl; cout << reverse(12345) << endl; system("pause"); }
时间: 2024-10-14 00:51:16