问题描述:
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
.
Example 1:
Input: a = "11",b = "1" Output: "100"
Example 2:
Input: a = "1010",b = "1011" Output: "10101"
解题思路:
我原来的代码巨长无比(就是正常的思路)
想看看有没有人又简短的代码。
我就知道,一定有。
代码:
class Solution { public: string addBinary(string a,string b) { int len1 = a.size(); if(len1 == 0) return b; int len2 = b.size(); if(len2 == 0) return a; int c = 0,i = len1-1,j = len2-1; string s; while(c > 0 || i > -1 || j > -1){ c += i > -1 ? a[i--] - ‘0‘ : 0; c += j > -1 ? b[j--] - ‘0‘ : 0; s.push_back(char(c%2 + ‘0‘)); c = c/2; } reverse(s.begin(),s.end()); return s; } };
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。