Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
思路:并没有什么特殊的……用一个long int来防止溢出并检验溢出
class Solution {
public:
int reverse(int x) {
int n=0;
long int sum=0;
if(x<0){x=x*(-1);n=1;}
while(x!=0){
int r=x%10;
sum=sum*10+r;
x=x/10;
}
if(sum>2147483647||sum<-2147483647) return 0;
if(n)return (int)-sum;
return (int)sum;
}
};
Reverse Bits是相关的题目
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?