C/C++ 判断两个整数相乘是否溢出

 判断两int相乘是否溢出,目前找到的最正确方式:

int is_mul_overflow(int a, int b) {
if( a >= 0 && b >=0 ) {
return INT_MAX / a < b;
}
else if( a < 0 && b < 0 ) {
return INT_MAX / a > b;
}
else if( a * b == INT_MIN ) {
return 0;
}
else {
return a < 0 ? is_mul_overflow(-a, b) : is_mul_overflow(a, -b);
}
}

void check(int n1, int n2, int expect_ret, int case_n) {
int ret = is_mul_overflow(n1, n2);
if( expect_ret == is_mul_overflow(n1, n2) )
printf(
"test pass case:%d\n",case_n);
else
printf(
"test fail case:%d\n",case_n);
}

int main() {
int case_n = 0;
check(
1, 0x80000000, 0, ++case_n);
check(
-1, 0x80000000, 1, ++case_n);
check(
0x80000000, -1, 1, ++case_n);
check(
-1, 0x80000001, 0, ++case_n);
check(
0x80000001, -1, 0, ++case_n);
check(
1, 0x7fffffff, 0, ++case_n);
check(
0x7fffffff, 1, 0, ++case_n);
check(
2, 0x7fffffff, 1, ++case_n);
check(
0x7fffffff, 2, 1, ++case_n);
check(
0x7fffffff, -1, 0, ++case_n);
check(
-1, 0x7fffffff, 0, ++case_n);
check(
2, 0xc0000000, 0, ++case_n);
check(
0xc0000000, 2, 0, ++case_n);
check(
0x70000000, 2, 1, ++case_n);
check(
2, 0x70000000, 1, ++case_n);

printf(
"%x\n", INT_MIN);
printf(
"%x\n", INT_MAX);
return 0;
}

欢迎给出更多测试数据

posted @ 2011-09-12 17:05  DOF_KL  阅读(9928)  评论(4编辑  收藏  举报