由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 请问如何安全地reverse 一个integer
相关主题
reverse an integer 怎么判断是否 overflow 来着非常好的总结面试题准备,分享一下!
问个简单的atoi的问题onsite完,攒rp系列(二)
请教一道Leetcode 题, 多谢str2int中overflow该如何处理?
请教leetcode一道题经典题atoi的溢出处理
问个简单C reverse int弱弱的问一个问题
函数atoi的实现atoi的溢出处理的想法
关于atoi的overflowatoi overflow怎么办?
问个越界的问题问一个atoi overflow的问题
相关话题的讨论汇总
话题: int话题: reverse话题: integer话题: max话题: number
进入JobHunting版参与讨论
1 (共1页)
l*******o
发帖数: 791
1
看到过一个题目,给一个integer,要求把它reverse过来,有可能这个integer反过来
时会over flow。
如果检测是否会over flow呢?
l*********r
发帖数: 674
2
什么叫reverse? 25变成52?如果输入20呢?
l*******o
发帖数: 791
3
对,如果给52那么就输出25 ,如果给20就输出2
g*********s
发帖数: 1782
4
reverse the string, then compare with the string of INT_MAX lexically?
need both itoa() and atoi().

【在 l*******o 的大作中提到】
: 看到过一个题目,给一个integer,要求把它reverse过来,有可能这个integer反过来
: 时会over flow。
: 如果检测是否会over flow呢?

J********a
发帖数: 5208
5
input : a
output : b
int b = 0;
int max = INT_MAX / 10;
while (a > 0){
int a1 = a % 10;
if (b > (INT_MAX-a1) / 10) error overflow;
b = b * 10 + a1;
a = a / 10;
}

【在 g*********s 的大作中提到】
: reverse the string, then compare with the string of INT_MAX lexically?
: need both itoa() and atoi().

J********a
发帖数: 5208
6
另外这个solution显然不好,如果题目变成把两个6进制整数倒过来怎么办?

【在 g*********s 的大作中提到】
: reverse the string, then compare with the string of INT_MAX lexically?
: need both itoa() and atoi().

g*********s
发帖数: 1782
7
i didn't check the details but this one looks better.

【在 J********a 的大作中提到】
: input : a
: output : b
: int b = 0;
: int max = INT_MAX / 10;
: while (a > 0){
: int a1 = a % 10;
: if (b > (INT_MAX-a1) / 10) error overflow;
: b = b * 10 + a1;
: a = a / 10;
: }

l*******o
发帖数: 791
8

别以为我看不懂你得签名,哈哈哈

【在 J********a 的大作中提到】
: 另外这个solution显然不好,如果题目变成把两个6进制整数倒过来怎么办?
J********a
发帖数: 5208
9
...

【在 l*******o 的大作中提到】
:
: 别以为我看不懂你得签名,哈哈哈

h***n
发帖数: 276
10
to detect the overflow, you can take the last digit off the orginal number b
efore reverse, with one less digit, the modified number should not be overfl
ow
then after reversing, you patch the last digit to the reversed number given
you know the number of digits already, from now on, you have several ways to
detect overflow, depending on whether the number is signed or unsigned

【在 l*******o 的大作中提到】
: 看到过一个题目,给一个integer,要求把它reverse过来,有可能这个integer反过来
: 时会over flow。
: 如果检测是否会over flow呢?

1 (共1页)
进入JobHunting版参与讨论
相关主题
问一个atoi overflow的问题问个简单C reverse int
新鲜Google面经函数atoi的实现
大牛,过来讨论一下这道题关于atoi的overflow
请教一个reverse decimal number的问题问个越界的问题
reverse an integer 怎么判断是否 overflow 来着非常好的总结面试题准备,分享一下!
问个简单的atoi的问题onsite完,攒rp系列(二)
请教一道Leetcode 题, 多谢str2int中overflow该如何处理?
请教leetcode一道题经典题atoi的溢出处理
相关话题的讨论汇总
话题: int话题: reverse话题: integer话题: max话题: number