67. Add Binary
来源:互联网 发布:100m网络下载速度 编辑:程序博客网 时间:2024/05/01 17:58
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
用大数加法的思想,按位相加。
class Solution {public: string addBinary(string a, string b) { int i=a.size()-1; int j=b.size()-1; int t=0; string c; while(i>=0&&j>=0){ t+=a[i--]-'0'+b[j--]-'0'; c=char(t%2+'0')+c; t/=2; } while(i>=0){ t+=a[i--]-'0'; c=char(t%2+'0')+c; t/=2; } while(j>=0){ t+=b[j--]-'0'; c=char(t%2+'0')+c; t/=2; } if(t)c=char(t%2+'0')+c; return c; }};又看了看网上大神的代码,学习了。。。
class Solution {public: string addBinary(string a, string b) { string result = ""; int c = 0; int i = a.size() - 1; int j = b.size() - 1; while(i >= 0 || j >=0 ||c ==1) { c += i >= 0 ? a[i--] - '0':0; c += j >= 0 ? b[j--] - '0':0; result = char( c% 2 + '0') + result; c /= 2; } return result; }};
0 0
- [LeetCode]67.Add Binary
- LeetCode --- 67. Add Binary
- [Leetcode] 67. Add Binary
- [leetcode] 67.Add Binary
- 67. Add Binary
- 【leetcode】67. Add Binary
- 67. Add Binary
- [leetcode] 67.Add Binary
- [leetcode] 67. Add Binary
- 67. Add Binary
- 67. Add Binary
- 【Leetcode】67. Add Binary
- 67. Add Binary
- 67. Add Binary LeetCode
- 67. Add Binary
- 【LeetCode】67. Add Binary
- 67. Add Binary
- 67. Add Binary
- java基础知识
- 多线程编程基础知识
- 231. Power of Two
- 详细解释强力的图片加载框架 Glide的配置(顺便补充下CollapsingToolbarLayout的一些功能)
- Qt构建OpenCV3.1CMake报错Failed to download opencv_ffmpeg.dll
- 67. Add Binary
- public static void main(String args[]){ }中的String args[ ]
- iOS Core Data简单演练
- 学习linux步骤
- PDF如何转为SWF
- APNS推送以及app内部消息处理、本地通知的使用
- sobel算子
- Android studio如何导入library及jar包和so包
- Structs2中拦截器的使用与详解