?371. Sum of Two Integers(C++)
来源:互联网 发布:手机淘宝老版本官方 编辑:程序博客网 时间:2024/06/06 15:53
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example :
Given a = 1 and b = 2, return 3.
class Solution {public: int getSum(int a, int b) { return b == 0 ? a : getSum(a ^ b, (a & b) << 1); }};
https://discuss.leetcode.com/topic/50315/a-summary-how-to-use-bit-manipulation-to-solve-problems-easily-and-efficiently
补充位运算符相关知识:
Set negation ALL_BITS ^ A or ~A
Set bit A |= 1 << bit
Clear bit A &= ~(1 << bit)
Test bit (A & 1 << bit) != 0
Extract last bit A&-A or A&~(A-1) or x^(x&(x-1))
Remove last bit A&(A-1)
Get all 1-bits ~0
Examples
//Count the number of ones in the binary representation of the given numberint count_one(int n) { while(n) { n = n&(n-1); count++; } return count;}
//Is power of four (actually map-checking, iterative and recursive methods can do the same)bool isPowerOfFour(int n) { return !(n&(n-1)) && (n&0x55555555); //check the 1-bit location;}
阅读全文
0 0
- 371. Sum of Two Integers(C++)
- ?371. Sum of Two Integers(C++)
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 在linux下的apache配置https协议,开启ssl连接
- table标签表格宽高失效以及前端知识回顾
- Android系统广播大全及开机自启的service
- 安装配置Android开发环境SDK
- Android异步处理技术
- ?371. Sum of Two Integers(C++)
- 模仿快捷分享、从下往上弹出窗口,自定义分享菜单
- android中ActionBar
- RCNN学习笔记(1):Rich feature hierarchies for accurate object detection and semantic segmentation
- TI-CC2640R2-Sensor Controller 开发应用
- Linux for Ubuntu 解决WPS安装缺少libpng12-0的问题
- 搭建FTP服务 搭建Http静态服务器环境
- mysql5.7 启用gtid,导致无法创建和删除表
- HashMap