Leetcode 67. Add Binary (Easy) (cpp)

来源:互联网 发布:stc89c52单片机简介 编辑:程序博客网 时间:2024/05/29 03:46

Leetcode 67. Add Binary (Easy) (cpp)

Tag: Math, String

Difficulty: Easy


/*67. Add Binary (Easy)Given two binary strings, return their sum (also a binary string).For example,a = "11"b = "1"Return "100".*/class Solution {public:    string addBinary(string a, string b) {        int i = a.size(), j = b.size(), carry = 0;        string res;        while (i > 0 || j > 0 || carry > 0) {            int num1 = i > 0 ? a[(i--) - 1] - '0' : 0, num2 = j > 0 ? b[(j--) - 1] - '0' : 0;            carry += num1 + num2;            res = char(carry % 2 + '0') + res;            carry /= 2;        }        return res;    }};


0 0
原创粉丝点击