[Leetcode] Add Binary
来源:互联网 发布:数据标注是什么 编辑:程序博客网 时间:2024/05/29 16:29
题目:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
思路:从后向前计算。尽量避免insert(0, "string")这样的操作,会重复分配内存。
class Solution {public: string addBinary(string a, string b) { int a_ptr = (int)a.size() - 1; int b_ptr = (int)b.size() - 1; int carry = 0; string result((a_ptr > b_ptr ? a_ptr : b_ptr) + 1, '\0'); for (int i = (int)result.size() - 1; i >= 0; --i) { int a_digit; if (a_ptr < 0) { a_digit = 0; } else { a_digit = a[a_ptr] - '0'; a_ptr--; } int b_digit; if (b_ptr < 0) { b_digit = 0; } else { b_digit = b[b_ptr] - '0'; b_ptr--; } result[i] = (a_digit + b_digit + carry) % 2 + '0'; carry = (a_digit + b_digit + carry) / 2; } if (carry > 0) { result.insert(0, "1"); } return result; }};
总结:复杂度O(n),n为a和b中较长的串的长度。
0 0
- 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
- 学到老活到老
- 关于正则表达式——元字符
- 做java开发这一年
- 【Linux】【CGI】cgic: CGI的C函数库
- Count and Say LeetCode:Mysolution
- [Leetcode] Add Binary
- 【Linux】【CGI】【FAQ】代码中字符格式问题——类似 error: stray ‘\357’ in program
- PM竞品分析(Competitive Analysis)
- C语言学习笔记(1)--基本概念和函数用法
- 【HDU】 1018 Big Number
- 树
- 如何创建并运行java线程
- 第七周项目三(2)求三数最大值
- 阿里面试经历及总结(数据挖掘)+个人学习经历