您的位置:首页 > 编程语言 > C语言/C++

leetcode题目: Reverse Integer 的C语言解法

2018-03-07 20:30 543 查看
题目的链接

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 hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

题目算不得难,但写的时候也出现了挺多问题。数值溢出是一个我没有考虑到的问题。因为定义的函数是int类型,而int的存储范围为2^31,需要一个位置来放符号,即实际范围为 -2147483648~2147483647。也就是题设最后说明的 如果数字倒置后数值溢出则返回0 这一情况。

#include <stdio.h>
#include <math.h>

int reverse(int x) {
int i = 0, j = 0;
long int sum = 0;
long int tem = abs(x);

while (tem != 0 )
{
tem = tem / 10;
j++;
}

tem = abs(x);

while (tem != 0) {
i = tem % 10;
tem = (tem - i) / 10;
j--;
sum = sum + i * pow(10, j);

}

if (x < 0)
sum = -sum;

if (sum < -2147483648 || sum >2147483647)
return 0;
else
return sum;
}

int main()
{
int x = -123;

printf("%d\n", reverse(x));
return 0;
}


程序中调用的函数也就几个幂函数以及绝对值函数,虽然有些繁琐,但用来解决符号方面可能出现的问题还是挺直观的。在最后的调试环节,我开始还是用的老方法,打断点后逐步执行找到数值突变的点(也就是数值溢出发生的语句),不过在这种类型题中有一种更为简单的调试方法:在循环后直接打印输出数值,找到错误后再把输出语句给删除。这样比逐步执行要简便且直观的多。

最后再附上哥哥写的简便版代码:

#include <limits.h>

int reverse(int x)
{
long long re = 0;
while(x){
re = re * 10 + x % 10;
x /= 10;
}
return re > INT_MIN && re < INT_MAX ? re : 0;
}


这个思路要比我的要简便很多。我的想法是逐步先遍历出数字的位数,之后每次取余好让这个数字倒置过来,这样就多了一轮循环。re不用int定义,直接就避免溢出,最后在return时再进行判定,倘若是溢出的值则返回0,否则就直接输出。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: