首页 > 其他 > 详细

LeeCode from 0 —— 67. Add Binary

时间:2018-07-12 21:05:17      阅读:140      评论:0      收藏:0      [点我收藏+]

67. Add Binary

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.

解题思路:

1)将每一位字符都转换为数字,将两个字符串对应位的数字相加。若需要进位,则保存进位的值并在下一次相加时加上进位。对应位若不存在则设为0,相加。

2)若两个字符串所有对应位相加结束,判断最后一个进位是否为1,若为1,则在字符串最前面补1.

C++代码如下:

class Solution {
public:
string addBinary(string a, string b) {
                        int n=a.length()-1;
                        int m=b.length()-1;
                        int p=0;
                        string c="" ;
                        while(n>=0 || m>=0){
                                   int i= n>=0 ? a[n--]-‘0‘:0;
                                   int j= m>=0 ? b[m--]-‘0‘:0;
                                   int sum=i+j+p;
                                  c=to_string(sum%2)+c;
                                  p=sum/2;
                       }
                      c= p==1 ? ‘1‘+c :c;
                      return c;

  }
};

LeeCode from 0 —— 67. Add Binary

原文:https://www.cnblogs.com/ssml/p/9301825.html

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