正文
LeetCode 7. Reverse Integer(c语言版)
小程序:扫一扫查出行
【扫一扫了解最新限行尾号】
复制小程序
【扫一扫了解最新限行尾号】
复制小程序
题目:
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
题解:
因为还不太会用c++和java,所以用c语言写的,题意很好理解,题也很简单,但需要注意溢出的问题,输入没有溢出,但翻转可能有溢出。
代码:
int reverse(int x) {
long long y=; //用longlong为了看是否有溢出
if(x>=pow(,)-||x<=-pow(,)) return ;
while(x!=)
{
int v=x%;
y=y*+v;
if(y>pow(,)-||y<-pow(,)) return ;
x/=;
}
int n=y;
return n;
}