[LeetCode]Add Binary
2013-12-16 13:35
459 查看
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()==0) return b; if(b.length()==0) return a; int len=a.length()<b.length()?a.length():b.length(); if(len==a.length()) swap(a,b); int len1=a.length(); int len2=b.length(); int i; for(i=0;i<len;i++) { a[len1-1-i]=(a[len1-1-i]-'0')+(b[len2-1-i]-'0')+'0'; } for(i=len1-1;i>0;i--) { if(a[i]>='2') { a[i]=(a[i]-'0')%2+'0'; a[i-1]=(a[i-1]-'0'+1)+'0'; } } if(a[0]>='2') { string ans(a,1,len1-1); if(a[0]=='2') return "10"+ans; else return "11"+ans; } else return a; } };
相关文章推荐
- node-webkit播放目录下所有网页文件
- Java--设计模式之代理模式
- SQLSERVER2008--日志收缩 or 日志清理
- 去掉CodeIgniter URL中的index.php
- activity之间数据传递方式
- 智能指针
- linux grep/egerp(每日一令之十二)
- Visual C# .Net 环境中编程实现浮动工具栏
- rabbitmq使用说明--good
- unity3d中的http通信
- oracle游标的简单学习
- ORACLE的TO_CHAR函数详解
- 重写系统Crash处理类,保存Crash信息到SD卡 和 完美退出程序的方法
- 中断控制电机反向转动
- Xcode编写C/C++程序
- 导入项目出现乱码的解决办法
- yacc语法笔记
- 心理学分析编程能力的四种境界
- 一个库搞定各种分享--ShareSDK
- 如何判断Linux是否适合你