Redian新闻
>
请问如何安全地reverse 一个integer
avatar
请问如何安全地reverse 一个integer# JobHunting - 待字闺中
l*o
1
看到过一个题目,给一个integer,要求把它reverse过来,有可能这个integer反过来
时会over flow。
如果检测是否会over flow呢?
avatar
l*r
2
什么叫reverse? 25变成52?如果输入20呢?
avatar
l*o
3
对,如果给52那么就输出25 ,如果给20就输出2
avatar
g*s
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呢?

avatar
J*a
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().

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

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

avatar
g*s
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;
: }

avatar
l*o
8

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

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

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

avatar
h*n
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呢?

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。