问题描述
Given a 32-bit signed integer, reverse digits of an integer.
假如给你一个32位的有符号整数,将该整数的各个数位反转
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.
假设我们使用的环境仅仅可以存储32位的整型数据,范围是[−231, 231 − 1]。如果反转之后的数字处理过后溢出,那就返回0.
思路分析
简介:主要是通过对10进行求余运算,获得最后一位,然后将原数对10进行整除,缩小一位。反复进行,直至剥夺了所有的位数。
代码
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
long reverse(int x);
int main()
{
int a;
long reversed = 0;
printf("please input the number ");
scanf("%d",&a);
reversed = reverse(a);
printf("reversed number is %ld",reversed);
return 0;
}
long reverse(int x)
{
long edge = pow(2,31);
long goal = 0,temp = 0;
while(x != 0)
{
temp = x % 10;
x = x / 10;
goal = goal * 10 + temp;
}
if(goal >= -edge && goal <= (edge - 1 ))
{
return goal;
}
else
{
return 0;
}
}
借鉴
class Solution {
public:
int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > INT_MAX/10 || (rev == INT_MAX / 10 && pop > 7)) return 0;
if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
};
总结
- 基本思想一致,通过求余和整除模仿出栈和入栈,从而实现数字的反转。
- 不同的是应对的溢出的策略和方法,我直接引用的长整型容纳数据,在最后的输出部分进行判定,增加了程序的内存占用。
- 全部都使用的int类型的,占用的内存空间比较小。