leetcode-add binary
2015-01-09 06:06
344 查看
Given two binary strings, return their sum (also a binary string).
For example,
a =
b =
Return
public class Solution {
public String addBinary(String a, String b) {
int idx1=a.length()-1,idx2=b.length()-1;
int carry=0;
StringBuffer result=new StringBuffer();
while(idx1>=0||idx2>=0||carry>0){
int sum=0;
sum+=carry;
if(idx1>=0){sum+=(a.charAt(idx1)-'0');idx1--;}
if(idx2>=0){sum+=(b.charAt(idx2)-'0');idx2--;}
carry=sum/2;
sum=sum%2;
result.append(sum); // this is char
}
return result.reverse().toString();
}
}
和两个数相加是相同的想法,都是由三个部分组成。然后注意的问题:
append 里面直接就把int变成char类型了。
出问题的:居然while中的idx2写成idx1了
For example,
a =
"11"
b =
"1"
Return
"100".
public class Solution {
public String addBinary(String a, String b) {
int idx1=a.length()-1,idx2=b.length()-1;
int carry=0;
StringBuffer result=new StringBuffer();
while(idx1>=0||idx2>=0||carry>0){
int sum=0;
sum+=carry;
if(idx1>=0){sum+=(a.charAt(idx1)-'0');idx1--;}
if(idx2>=0){sum+=(b.charAt(idx2)-'0');idx2--;}
carry=sum/2;
sum=sum%2;
result.append(sum); // this is char
}
return result.reverse().toString();
}
}
和两个数相加是相同的想法,都是由三个部分组成。然后注意的问题:
append 里面直接就把int变成char类型了。
出问题的:居然while中的idx2写成idx1了
相关文章推荐
- LeetCode – Refresh – Add Binary
- 【leetcode】String——Add Binary(67)
- LeetCode : Add Binary
- LeetCode--Add Binary
- LeetCode Add Binary
- [LeetCode 67] Add Binary
- LeetCode---Add Binary
- [LeetCode] Add Binary
- 【LeetCode】Add Binary
- LeetCode Add Binary
- LeetCode(67)题解: Add Binary
- LeetCode: Add Binary
- Add Binary -- leetcode
- 《leetCode》:Add Binary
- LeetCode笔记:67. Add Binary
- *(leetcode_string) Add Binary
- Sum—LeetCode-67 Add Binary
- LeetCode小白菜笔记[16]:Add Binary
- leetcode_Add Binary
- Add Binary--LeetCode