Add Binary
2015-12-07 15:17
239 查看
Given two binary strings, return their sum (also a binary string).
For example,
a =
b =
Return
For example,
a =
"11"
b =
"1"
Return
"100".
class Solution { public: string addBinary(string a, string b) { if(a.length()<b.length()){ string zeros(b.length()-a.length(),'0'); a = zeros + a; }else{ string zeros(a.length()-b.length(),'0'); b = zeros + b; } string result; int next = 0; for(int i = a.length()-1;i>=0;i--){ int sum = (a[i] - '0') + (b[i] - '0') + next; switch(sum){ case 0: result = '0' + result; next = 0; break; case 1: result = '1' + result; next = 0; break; case 2: result = '0' + result; next = 1; break; default: result = '1' + result; next = 1; } } if(next != 0){ result = '1' + result; } return result; } };
相关文章推荐
- BI使用者的角色
- [Linux主机] 优化你的php-fpm(php5.3+)让你的网站跑得更快
- Service和BroadCast配合使用
- Post请求相关整理
- set -x
- XML在Qt中的使用
- 堆维护
- 判别分析——逻辑斯蒂回归
- excel怎么固定第一行
- 外部中断(红外通信)
- org.hibernate.transaction.JDBCTransaction cannot be cast to javax.transaction.Transaction
- rhel 6.5 安装yum源
- 地表最强! Unity 5.x 插件合集专用贴 - 更新日期 2015.12.06
- Picasso图片下载缓存库的使用心得
- TF10187:Could not open document XXX.dbmdl
- VisualSVN Server添加svn项目
- IOS应用安全(五):高级Runtime分析和操作
- oracle 自增ID
- CSS中zoom和scale的区别
- Jenkins中Jelly基础、超链接、国际化