首页 > 其他 > 详细

Add Binary - LeetCode

时间:2015-10-25 07:26:05      阅读:201      评论:0      收藏:0      [点我收藏+]

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 };

 

Add Binary - LeetCode

原文:http://www.cnblogs.com/fenshen371/p/4908186.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!