贴两道灵活运用位运算知识来解题的
2016-07-10 23:23
405 查看
1.
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
a,b为整数,a异或(^)b得到的值是不加上进位值的结果,然后(a&b)<<1得到的是所有进位的值,加起来就行了,但是这里加起来还有进位怎么办呢,那就迭代加,如上。
2.
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
一位加法器算a+b,用
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
class Solution { public: int getSum(int a, int b) { while(b){ int result = a ^ b; int carry = (a & b)<<1; a = result,b = carry; } return a; } };
a,b为整数,a异或(^)b得到的值是不加上进位值的结果,然后(a&b)<<1得到的是所有进位的值,加起来就行了,但是这里加起来还有进位怎么办呢,那就迭代加,如上。
2.
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
string addBinary(string a, string b) { int alen = a.size(); int blen = b.size(); bool carry = false; string result; while( alen>0 || blen>0) { int abit = alen<=0 ? 0 : a[alen-1]-'0'; int bbit = blen<=0 ? 0 : b[blen-1]-'0'; int cbit = carry ? 1 : 0; result.insert(result.begin(), '0' + ((abit+bbit+cbit) & 1) );// here is the key point carry = (abit+bbit+cbit>1); alen--; blen--; } if (carry){ result.insert(result.begin(), '1'); } return result; }
一位加法器算a+b,用
(a+b)&1就能得到低位正确的值了,然后carry的值等于
(a+b)>>1或者
a+b>1。
相关文章推荐
- 了解微服务
- 驱动介绍xx
- 使用Visual Studio Code开发Asp.Net Core WebApi学习笔记(二)-- Web Api Demo
- Androi 4000 d的基础简介
- operator new之签名式new/delete(signature operator new/delete)
- shell 脚本中常用字符含义与vim编辑器中的快捷键
- php如何使用文件锁
- ui router 介绍
- Java8系列之重新认识HashMap
- Selenium和firefox兼容性问题
- PAT乙级练习题B1042. 字符统计
- 向量运用-判断方向
- 315. Count of Smaller Numbers After Self
- python学习日记——1
- C++多线程
- C++ primer plus笔记整理 05
- 无序字母对
- hive和impala查询数据对比
- spring bean 入门
- 7_6_P题 Wall 题解[poj 1113] (凸包)