本文主要是介绍67. Add Binary(Leetcode每日一题-2020.06.23),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Problem
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Constraints:
- Each string consists only of ‘0’ or ‘1’ characters.
- 1 <= a.length, b.length <= 10^4
- Each string is either “0” or doesn’t contain any leading zero.
Example1
Input: a = “11”, b = “1”
Output: “100”
Example2
Input: a = “1010”, b = “1011”
Output: “10101”
Solution
class Solution {
public:string addBinary(string a, string b) {string ret = "";int i = a.length() - 1;int j = b.length() - 1;int carry = 0;while(i >= 0 || j >=0 || carry != 0){int a_val = i >= 0 ? a[i] - '0' : 0;int b_val = j >= 0 ? b[j] - '0' : 0;int sum = a_val + b_val + carry;int val = sum % 2;carry = sum / 2;ret = to_string(val) + ret;--i;--j;}return ret;}
};
这篇关于67. Add Binary(Leetcode每日一题-2020.06.23)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!