[LeetCode]—Add Binary 两个字符串二进制相加
2014-07-02 20:28
399 查看
Add Binary
Given two binary strings, return their sum (also a binary string).For example,
a =
"11"
b =
"1"
Return
"100".
思路简单,代码要写的简洁高效才好。
#include<iostream> #include<string> #include<sstream> #include<algorithm> using namespace std; class Solution { public: string addBinary(string a, string b) { int len_a=a.length(); int len_b=b.length(); int carry=0,temp; string res=""; int len=max(len_a,len_b); for(int i=0;i<len;i++){ int p=(i<len_a)?a[len_a-1-i]-'0':0; int q=(i<len_b)?b[len_b-1-i]-'0':0; temp=p+q+carry; carry=temp/2; res.insert(res.begin(),temp%2+'0'); } return (carry==0)?res:"1"+res; } };
相关文章推荐
- 每天一道LeetCode-----将用数组表示的整数加一,两个用字符串表示的(二进制)数相加
- Add Binary 两个二进制字符串相加
- LeetCode425——Add Strings(两个字符串中的数字相加(十进制或二进制),输出字符串形式的结果)
- leetcode_415(两个数字字符串相加,模拟大数相加)
- leetcode 67. Add Binary 二进制相加
- LeetCode 67 Add Binary(二进制相加)(*)
- LeetCode之二进制字符串相加
- LeetCode-67-Add Binary(二进制相加)
- LeetCode | Add Binary(二进制相加)
- LeetCode 67. Add Binary (二进制相加)
- leetcode_318. Maximum Product of Word Lengths 求两个不相交的字符串的长度乘积的最大值,将字母转换成二进制形式,按位与比较是否有相同字母
- LeetCode 67 Add Binary(二进制相加)(*)
- [LeetCode]-Edit Distance 两个字符串之间最小编辑距离
- java两个字符串数字相加
- LeetCode 之 two Sum寻找两个相加之和为给定值的两个数
- 两个大数相加,使用字符串模拟相加过程
- LeetCode—**Edit Distance 计算两个字符串之间的距离
- Add Binary 二进制相加
- leetCode 之 两个二进制数相加
- LeetCode | Add Two Numbers(两个链表相加)