Add Binary

来源:互联网 发布:淘宝都是天猫 编辑:程序博客网 时间:2024/04/30 02:10

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) {        string result="";        int lenA=a.size();        int lenB=b.size();        int jinwei=0;        for(int i=lenA-1,j=lenB-1;i>=0||j>=0||jinwei==1;i--,j--){            jinwei += i >= 0 ? a[i] - '0' : 0;            jinwei += j >= 0 ? b[j] - '0' : 0;            result =  char(jinwei % 2 + '0')+result;            jinwei /= 2;        }        return result;    }};


0 0
原创粉丝点击