Add Binary leetcode
来源:互联网 发布:伪随机算法公式 编辑:程序博客网 时间:2024/05/27 09:44
Add Binary
Apr 2 '12
5763 / 16556
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
我的丑陋的
public class Solution { public String addBinary(String a, String b) { if(a==null||b==null) return null; int la = a.length(),lb = b.length(); int add = 0; int i = la-1,j=lb-1; StringBuilder sb = new StringBuilder(); while(i>=0 && j>=0){ int sum =( a.charAt(i)-'0') +b.charAt(j)-'0'+add; add = sum/2; sum = sum%2; sb.insert(0,sum+""); i--; j--; } if(i>=0){ j=i; b=a; } while(j>=0){ int sum = b.charAt(j)-'0'+add; // add = sum/2; sum = sum%2; sb.insert(0,sum+""); j--; } if(add>0){ sb.insert(0,"1"); // } return sb.toString(); }}
别人的比较优美的写法
class Solution {public: string addBinary(string a, string b) { // Start typing your C/C++ solution below // DO NOT write int main() function int la = a.size(); int lb = b.size(); string sum = la > lb ? a : b; int overflow = 0; for( int i = 0; i < sum.size(); i ++ ) { char ca = i < la ? a[la - i - 1] : '0'; char cb = i < lb ? b[lb - i - 1] : '0'; int bit = ca - '0' + cb - '0' + overflow; overflow = bit / 2; sum[sum.size() - i - 1] = bit % 2 + '0'; } if(overflow) { sum = "1" + sum; } return sum; }};
- LeetCode: Add Binary
- [Leetcode] Add Binary
- LeetCode Add Binary
- Leetcode: Add Binary
- [Leetcode] Add Binary
- LeetCode : Add Binary
- LeetCode Add Binary
- [LeetCode] Add Binary
- leetcode 58: Add Binary
- leetcode Add Binary
- [LeetCode] Add Binary
- 【leetcode】Add Binary
- [LeetCode]Add Binary
- [leetcode]Add Binary
- LeetCode-Add Binary
- [leetcode] Add Binary
- LeetCode - Add Binary
- leetcode:Add Binary
- 界面常用的颜色
- C#入门经典—第六章
- ThinkPHP session方法
- E325:ATTENTION
- Http 断点续传
- Add Binary leetcode
- webGL开源库
- 如何解决IE8中select控件多选控件在焦点不在控件上时点击选项要点击两次才能选中的问题
- Android中SQLiteDatabase操作【附源码】
- LINUX 使用 smbclient 获取windows 共享目录的文件 详解
- acer 4560G在Ubuntu10.04系统下的有线网络无法连接的问题
- ZOJ 2797 POJ 2472 106 miles to Chicago
- 大于2T的磁盘使用GPT分区方式
- ThinkPHP cookie方法