Add Binary
来源:互联网 发布:c语言lib文件 编辑:程序博客网 时间:2024/04/30 05:11
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
思路:就是模拟bit 加法运算,用stringbuilder,注意insert(0,val)是加到最前面;
public class Solution { public String addBinary(String a, String b) { if(a == null && b == null) return null; if(a != null && b == null) return a; if(a == null && b != null) return b; StringBuilder sb = new StringBuilder(); int i = 0; int j = 0; int carry = 0; while(i<a.length() || j<b.length() || carry != 0){ int av = 0; if(i<a.length()){ av = a.charAt(a.length()-1-i)-'0'; i++; } int bv = 0; if(j<b.length()){ bv = b.charAt(b.length()-1-j)-'0'; j++; } int sum = av + bv + carry; sb.insert(0, sum %2); carry = sum / 2; } return sb.toString(); }}
0 0
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- 即时通信方案
- 解決 Tomcat Server in Eclipse unable to start within 45 seconds 啟動過久的錯誤
- C# Setup项目修改默认安装路径
- iOS 带IAP提交注意事项及无法submit for review的解决方案
- ios 字符串动态大小
- Add Binary
- Linux汇编语言开发指南
- ubuntu下安装subversion客户端
- (十一)Spring2.5中placeholder讲解既怎样在配置文件中引用外部的资源文件
- android多媒体框架学习
- c#设计模式-Factory Pattern
- 《基于ORACLE SQL优化》读书笔记-访问索引的方法
- [Mugeda HTML5技术教程之13]链接的添加方式
- BIOS入口地址:FFFF:0000是指什么意思?在物理上是指内存条的什么位置?