Leetcode:Add Binary 二进制相加
2014-04-28 16:02
316 查看
Given two binary strings, return their sum (also a binary string).
For example,
a =
b =
Return
思路同十进制的大数相加。代码如下:
For example,
a =
"11"
b =
"1"
Return
"100".
思路同十进制的大数相加。代码如下:
class Solution { public: string addBinary(string a, string b) { size_t len_a = a.length(); size_t len_b = b.length(); if(len_a == 0) return b; if(len_b == 0) return a; int i = len_a - 1; int j = len_b - 1; int increase = 0; stack<int> result_stk; while(i >= 0 && j >= 0) { int s = a[i] - '0' + b[j] - '0' + increase; increase = s / 2; int sum = s % 2; result_stk.push(sum); i--; j--; } while(i >= 0) { int s = a[i] - '0' + increase; increase = s / 2; int sum = s % 2; result_stk.push(sum); i--; } while(j >= 0) { int s = b[j] - '0' + increase; increase = s / 2; int sum = s % 2; result_stk.push(sum); j--; } if(increase == 1) result_stk.push(1); string result; while(!result_stk.empty()) { result += result_stk.top() + '0'; result_stk.pop(); } return result; } };
相关文章推荐
- LeetCode OJ:Add Binary(二进制相加)
- 二进制字符串求和-leetcode Add Binary
- Add Binary 二进制相加 @LeetCode
- 67.LeetCode Add Binary(easy)[字符串 大数相加处理]
- (LeetCode)Add Binary --- 二进制求和
- Add Binary(二进制字符串相加)
- leetcode — add-binary
- leetcode之Add Binary
- 每天一道LeetCode-----将用数组表示的整数加一,两个用字符串表示的(二进制)数相加
- LeetCode Add Binary
- leetcode:add binary 菜鸟解法
- LeetCode OJ Add Binary
- Lettcode_67_Add Binary——给定两个二进制字符串返回其和
- leetcode_ Add to List 108. Convert Sorted Array to Binary Search Tree
- LeetCode 67 Add Binary(二进制相加)(*)
- [LeetCode] 2. Add Two Numbers 两个数字相加
- [LeetCode] Add Binary
- https://leetcode.com/problems/add-binary/
- [LeetCode]Add Binary&Climbing Stairs&Remove Duplicates from Sorted List
- leetcode 5. 两个链表逐个元素相加 Add Two Numbers