algorithm@ Divide two integers without using multiplication, division and mod operator. (Bit Operation)
2016-03-16 05:00
429 查看
#include<bits/stdc++.h> using namespace std; int divide(int dividend, int divisor) { long long n = dividend, m = divisor; // determine sign of the quotient int sign = n < 0 ^ m < 0 ? -1 : 1; // remove sign of operands n = abs(n), m = abs(m); // q stores the quotient in computation long long q = 0; // test down from the highest bit // accumulate the tentative value for valid bits for (long long t = 0, i = 31; i >= 0; i--) if (t + (m << i) <= n) t += m << i, q |= 1 << i; // assign back the sign if (sign < 0) q = -q; // check for overflow and return return q >= INT_MAX || q < INT_MIN ? INT_MAX : q; } int main() { cout << divide(-4, 20) << endl; return 0; }
相关文章推荐
- 《kali linux 渗透测试初级教程》免费下载
- 检测用户是否具有administrator权限(OpenThreadToken,OpenProcessToken,GetTokenInformation,AllocateAndInitializeSid和EqualSid)
- shell空数组
- shell二维数组
- CentOS7安装mysql5.7.11
- pthread mutex使用的一些思考
- shell一维数组
- 利用U盘在虚拟机上安装linux的插曲
- UVA 11361Investigating Div-Sum Property
- 使用 xsd.exe 命令工具将 xsd 架构生成 类(CS) 文件
- centos7 开发环境配置
- Centos 7 开启端口
- 从域名锁定该网站所在城市
- 在创业公司做架构师
- 最新精简型Linux桌面环境大比拼:LXDE Vs Xfce Vs MATE
- tomcat 启动报 操作系统找不到已输入的环境选项
- Linux用户管理笔记
- 网站运营思维导图模板
- 国内首家研发的在线直播网站系统
- 搭建nginx+tomcat+Java的负载均衡环境