由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 问个越界的问题
相关主题
经典题atoi的溢出处理关于atoi的overflow
问个简单C reverse int问一个atoi overflow的问题
onsite完,攒rp系列(二)reverse an integer 怎么判断是否 overflow 来着
请问如何安全地reverse 一个integer新鲜Google面经
str2int中overflow该如何处理?大牛,过来讨论一下这道题
弱弱的问一个问题为什么double和float不需要考虑overflow呢?
函数atoi的实现帮忙看看我写的atoi有没有bug, 谢谢
atoi overflow怎么办?atoi的溢出处理的想法
相关话题的讨论汇总
话题: int话题: sqr话题: bound话题: upper话题: 越界
进入JobHunting版参与讨论
1 (共1页)
a**********2
发帖数: 340
1
求int sqrt(int x)越界如何处理啊?

看到以前的一个帖子,觉得好像不太对, INT_MAX是2^31-1不是2^32,用(1<<16)还是
会越界,请问下该如何处理?
还有判断越界一般用什么方法?多谢了
a**********2
发帖数: 340
2
自己顶一下
i**********e
发帖数: 1145
3
Good observation.
You are correct, my previous post has bugs and did not address the overflow
issue properly.
Two methods to address:
i) find the upper bound of SQRT(INT_MAX) once and pass it into that function
. The upper bound can be found using a helper function that tests for
overflow. (ie, as soon as the condition when x > x*x is met, we knew x-1 is
the upper bound).
ii) declare the parameter x as unsigned int. Then initialize the upper bound
,
hi = min(n/2, (1<<16) - 1);
Hope this helps.

【在 a**********2 的大作中提到】
: 求int sqrt(int x)越界如何处理啊?
:
: 看到以前的一个帖子,觉得好像不太对, INT_MAX是2^31-1不是2^32,用(1<<16)还是
: 会越界,请问下该如何处理?
: 还有判断越界一般用什么方法?多谢了

i**********e
发帖数: 1145
4
This should also work too :)
The observation is when it overflows, it must be the case M > M*M, so
readjust the upper bound to M-1 when that happens.
int mysqrt(int n) {
int L = 0;
int H = min(n/2, (1<<16));
while (L < H) {
int M = L+(H-L+1)/2;
int M_sqr = M*M;
if (M <= M_sqr && M_sqr <= n)
L = M;
else /* M > M_sqr || (M_sqr > n) */
H = M-1;
}
return L;
}
k*j
发帖数: 153
5
or just test if M*M<0, if so then it overflows.

【在 i**********e 的大作中提到】
: This should also work too :)
: The observation is when it overflows, it must be the case M > M*M, so
: readjust the upper bound to M-1 when that happens.
: int mysqrt(int n) {
: int L = 0;
: int H = min(n/2, (1<<16));
: while (L < H) {
: int M = L+(H-L+1)/2;
: int M_sqr = M*M;
: if (M <= M_sqr && M_sqr <= n)

l*********8
发帖数: 4642
6
这个不能保证吧。

【在 k*j 的大作中提到】
: or just test if M*M<0, if so then it overflows.
1 (共1页)
进入JobHunting版参与讨论
相关主题
atoi的溢出处理的想法str2int中overflow该如何处理?
问一道乘法题弱弱的问一个问题
请问,string to long函数atoi的实现
请教一道Leetcode 题, 多谢atoi overflow怎么办?
经典题atoi的溢出处理关于atoi的overflow
问个简单C reverse int问一个atoi overflow的问题
onsite完,攒rp系列(二)reverse an integer 怎么判断是否 overflow 来着
请问如何安全地reverse 一个integer新鲜Google面经
相关话题的讨论汇总
话题: int话题: sqr话题: bound话题: upper话题: 越界