9、编程实现两个正整数的除法
2012-09-05 20:23
706 查看
/************************************************************************/ /* 9、编程实现两个正整数的除法 */ /************************************************************************/ // abs(x)/abs(y) = h, 则 (h+1)* abs(y) > abs(x) >= h * y, 利用二分查找求h //找到满足条件的k, 时间复杂度o(1) int div1(const int x, const int y) { if(y == 0) throw new exception("divided by zero!"); if(x == 0) return 0; //保证x、y可以去到0xffffffff unsigned tempX = abs(x); unsigned tempY = abs(y); unsigned h = 1; unsigned hy = tempY; //最多32次 while(hy < tempX) { hy <<= 1; //tempY * 2 h <<= 1; } //最多31次 //result一定在[h/2, h)之间 [l, h) unsigned l = h >> 1; while(l < h - 1) { unsigned mid = (l + h) >> 1; //(l +h) /2 unsigned midy = mid * tempY; if(midy == tempX) { l = mid; break; } else if(midy < tempX) l = mid; else h = mid; } //判断符号 if((x > 0 && y < 0) || (x < 0 && y > 0)) return -1 * l; else return l; } void testOfDiv() { int x = rand() % 1000000; int y = rand()% 10000000; int ret1= 0; cout << "x/y" << endl; CLOCK { ret1 = x / y; } int ret2 = 0; cout << "div1(x/y)" << endl; CLOCK { ret2 = div1(x, y); } assert(ret1 == ret2); }
相关文章推荐
- 编程实现两个正整数的除法,当然不能用除法操作符
- [每日练习]编程实现两个正整数的除法
- 编程实现两个正整数的除法,当然不能用除法操作符。
- 编程实现两个正整数的除法,当然不能用除法操作符。
- 编程实现两个正整数的除法
- 编程实现两个正整数的除法
- 编程实现两个正整数的除法
- 微软面试题:编程实现两个正整数的除法
- 编程实现两个正整数的除法
- java-编程实现两个正整数的除法,当然不能用除法操作符
- 编程实现两个正整数的除法,当然不能用除法操作符
- 微软面试题:编程实现两个正整数的除法,当然不能用除法操作符。
- 编程实现两个正整数的除法,当然不能用除法操作符
- 结构之法 算法之道 面试题 9、编程实现两个正整数的除法 编程实现两个正整数的除法,当然不能用除法操作符。
- 微软面试题:编程实现两个正整数的除法,不能用除法操作符
- 编程实现两个正整数的除法
- 不用 "%" && "/" 编程实现两个正整数的除法,取余数
- 编程实现两个正整数的除法
- 编程实现两个正整数的除法
- 微软面试题:编程实现两个正整数的除法