1、leedcode 7. 整数反转
题目:
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−2^31, 2^31 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
分析:数值反转后可能会超过 int 的范围。超过范围,输出0;
1、上限超出,rev*10 + pop > INT_MAX, 即rev > (INT_MAX-pop)/10,此时要求pop>=0,否则INT_MAX-pop 超过上界;
2、下限超出,rev*10 + pop < INT_MIN, 即rev > (INT_MIN-pop)/10,此时要求pop>=0,否则INT_MIN-pop 超过下界;
代码:
class Solution {
public:
int reverse(int x) {
int rev = 0;
int pop;
while(x!=0){
pop = x%10;
x = x/10;
if(pop>=0 && rev > (INT_MAX-pop)/10) return 0;
if(pop<=0 && rev < (INT_MIN-pop)/10) return 0;
//if(rev>INT_MAX/10 || rev==INT_MAX/10 && pop>INT_MAX%10) return 0;
//if(rev<INT_MIN/10 || rev==INT_MIN/10 && pop<INT_MIN%10) return 0;
rev = rev*10+pop;
}
return rev;
}
};
2、PAT A
1065 A+B and C (64bit) (20分)
Given three integers A, B and C in [−263,263], you are supposed to tell whether A+B>C.
Input Specification:
The first line of the input gives the positive number of test cases, T (≤10). Then T test cases follow, each consists of a single line containing three integers A, B and C, separated by single spaces.
Output Specification:
For each test case, output in one line Case #X: true
if A+B>C, or Case #X: false
otherwise, where X is the case number (starting from 1).
Sample Input:
3
1 2 3
2 3 4
9223372036854775807 -9223372036854775808 0
Sample Output:
Case #1: false
Case #2: true
Case #3: false
分析:反码:0,000.....00 ...... 0, 111.....11 (+0 ..... +2^63-1)
1,000....00 ....... 1,111....11 (-2^63.....-1)
A>0; B>0; A+B超界取值范围是(-2^63.....-2)
A<0; B<0; A+B超界取值范围是 (0........2^63-1)
代码:
#include<iostream>
using namespace std;
int main()
{
int n;
cin >>n;
for(int i=1; i<=n; i++)
{
long long a, b, c, ans;
cin >> a >> b >> c;
ans = a+b;
if(a>0 && b>0 && ans<0)
cout << "Case #" << i << ": true\n";
else if(a<0 && b<0 && ans>=0)
cout << "Case #" << i << ": false\n";
else if(ans > c)
cout << "Case #" << i << ": true\n";
else
cout << "Case #" << i << ": false\n";
}
return 0;
}