Add Binary - LeetCode

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

思路:学习这种代码的简洁写法。

 1 class Solution {
 2 public:
 3     string addBinary(string a, string b) {
 4         string res;
 5         int ia = a.size() - 1, ib = b.size() - 1, c = 0;
 6         while (ia >= 0 || ib >= 0 || c == 1)
 7         {
 8             c += (ia >= 0) ? (int)(a[ia--] - '0') : 0;
 9             c += (ib >= 0) ? (int)(b[ib--] - '0') : 0;
10             res = (char)(c % 2 + '0') + res;
11             c = c >> 1;
12         }
13         return res;
14     }
15 };

 

posted @ 2015-10-25 06:50  fenshen371  阅读(110)  评论(0编辑  收藏  举报