[LeetCode4]Add Binary
来源:互联网 发布:pc淘宝规蜜入口在哪里 编辑:程序博客网 时间:2024/05/22 21:00
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
Analysis:
The idea is simple. Use carry and current digit number. notice the calcuate order.
Java
public String addBinary(String a, String b) { int carry = 0; StringBuffer result = new StringBuffer(); for(int i=a.length()-1,j=b.length()-1;i>=0||j>=0;i--,j--){ int a1 = i>=0? (a.charAt(i)-'0'):0; int b1 = j>=0? (b.charAt(j)-'0'):0; int digit = (a1+b1+carry)%2; carry = (a1+b1+carry)/2; result.insert(0, digit); } if(carry==1) result.insert(0, '1'); return result.toString(); }c++
string addBinary(string a, string b) { string result; reverse(a.begin(),a.end()); reverse(b.begin(),b.end()); int maxL = a.size()>b.size() ? a.size() : b.size(); int carry = 0; for(int i=0; i<maxL; i++){ int la = i<a.size()? a[i]-'0':0; int lb = i<b.size()? b[i]-'0':0; int sum = (la+lb+carry)%2; carry = (la+lb+carry)/2; result.insert(result.begin(),sum+'0'); } if(carry == 1) result.insert(result.begin(),'1'); return result; }
ps:
如果把二进制换成16进制,怎么做。 facebook面试题
0 0
- [LeetCode4]Add Binary
- LeetCode4: Add Two Numbers
- leetcode4-Add Two Num
- LeetCode4 Add Digits
- leetcode4
- leetcode4
- leetcode4
- leetcode4
- LeetCode4
- leetcode4: Binary Tree Maximum Path Sum
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- ARM中,总线如何连接?
- extern C的作用详解
- swift菜鸟入门视频教程-01-基础部分
- 自己手工打造的DBUTIL包(源码1)
- 自己开发的Dbutile包(源码2)
- [LeetCode4]Add Binary
- 苹果iPad Air 2机模曝光:加入指纹传感器
- CCNP路由实验之七 动态路由之BGP
- Java常用类之Calendar类——诺诺"涂鸦"记忆
- Java学习笔记二
- Swift学习笔记(一)
- SharpMap增加标注图层LabelLayer及标注样式控制
- 关于tomcat常遇到的问题
- 学习札记 ----wind7下如何安装SqlServer数据库