Easy 67题 Add Binary
来源:互联网 发布:国际网络电话软件排名 编辑:程序博客网 时间:2024/05/29 02:36
Question:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
Solution:
public class Solution { public String addBinary(String a, String b) { StringBuilder sb=new StringBuilder(); int flag=0; int i=a.length(); int j=b.length(); int first=0; int second=0; int enda=0; int endb=0; for(;i>=0&&j>=0;) { if(i==0){ first=0; enda=1; } else{ first=Integer.valueOf(a.substring(i-1,i)); i--; } if(j==0){ second=0; endb=1; } else{ second=Integer.valueOf(b.substring(j-1,j)); j--; } if(enda+endb==2) break; Integer tmp=(first^second)^flag; sb.insert(0, tmp.toString()); if(first+second+flag>=2) flag=1; else flag=0; } if(flag==1) sb.insert(0,"1"); return sb.toString(); }}另一种discussion上的简化写法,注意循环条件的变化
StringBuilder sb=new StringBuilder(); int i=a.length()-1; int j=b.length()-1; int carry=0; while(i>=0||j>=0) { int sum = carry; if (j >= 0) sum += b.charAt(j--) - '0'; if (i >= 0) sum += a.charAt(i--) - '0'; sb.insert(0,sum%2); carry=sum/2; } if(carry!=0) sb.insert(0,'1'); return sb.toString();
0 0
- Easy 67题 Add Binary
- [Leetcode 67, easy] Add Binary
- 【LeetCode】(67)Add Binary (Easy)
- <LeetCode><Easy> 67 Add Binary
- Easy 15 Add Binary(67)
- Leetcode OJ 67 Add Binary [Easy]
- 【leetcode】Add Binary[easy]
- 67. Add Binary [easy] (Python)
- 67.Add Binary(String-Easy)
- LeetCode-67-Add Binary(数字/字符串处理)-Easy
- Easy-题目55:67. Add Binary
- Leetcode 67. Add Binary (Easy) (cpp)
- LeetCode-Easy刷题(14) Add Binary
- Easy 258题 Add Digital
- 67.LeetCode Add Binary(easy)[字符串 大数相加处理]
- LeetCode 第 67 题 (Add Binary)
- [67]Add Binary
- CODE 67: Add Binary
- Linux下spi驱动开发(1)
- Msql 中的 时间段查询(一天,一周,一个月)
- Linux下spi驱动开发(2)
- 出现Unknown class BMKMapView in Interface Builder file异常
- 豆瓣电影分析报告:大陆和港台到底差(cha)在哪里?
- Easy 67题 Add Binary
- NOIP 2010 - 提高组 关押罪犯 二分答案+二分图的判定
- 1622-5 孔富晨 总结《2016年10月5日》【连续第5天总结】
- 迭代带来数据疯狂(数据字典查询)
- Android Studio百度地图(BaiduMap)开发教程,
- 将二维数组作为参数的函数原型
- springmvc中的对象、数组、集合类型的参数绑定
- struts2+hibernate改造考勤系统备忘录(一)
- JAVA--File类