Reverse Integer
程序员文章站
2024-03-22 14:04:34
...
题目描述:
https://leetcode-cn.com/problems/reverse-integer/
思路:从原数中分离出各个位的数值,并且倒置即可。
#include<cstdio>
#include<iostream>
#include<math.h>
#include<stdlib.h>
using namespace std;
int reverse(int x)
{
//只有一位则直接返回该值
if(x<10&&x>-10)
return x;
int num = abs(x);
long result = 0;
//得到x是几位数
int length = 1;
while(((int)(num/pow(10,length)))!=0)
length += 1;
cout<<"length:"<<length<<endl;
//翻转x
while(length!=0)
{
int a = num%10;
result += a*pow(10,length-1);
length -= 1;
num /= 10;
}
result = x<0?((-1)*result):result;
//result超出界限则返回0
if(result>2147483647||result<-2147483648)
result = 0;
return result;
}
int main(){
int x = -321;
int result = reverse(x);
printf("%d\n",result);
return 0;
}
上一篇: 面向对象基础
下一篇: Reverse Integer