Leetcode9: Add Binary

243 篇文章 0 订阅

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

For example,
a = "11"
b = "1"

Return "100".


看看自己写的代码,渣的不行。把string先转成数字,相加后再对每一位判断是否大于1,最后生成的数字再转成string,真是完全不把string当回事啊~~为什么不直接在string上操作呢?而且转化为int,还有上限的问题,比如输入这两个"1110110101", "1110111011" ,结果是:"-1226763192"而不是"11101110000"!!真是被自己蠢哭~~

class Solution {
public:
    string addBinary(string a, string b) {
        int Inta = atoi(a.c_str());
        int Intb = atoi(b.c_str());
        int c = Inta + Intb;
        
        vector<int> temp;
        int flag = 0;
        int d;
        while(c)
        {
            d = c % 10;
            flag = d / 2;
            temp.push_back(d%2);
            c /= 10;
            c += flag;
        }
        
        int size = temp.size();
        d = 0;
        for(int i = size-1; i >= 0; i--)
        {
            d = d*10 + temp[i];
        }
        
        char str[size];
        sprintf(str, "%d", d);
        //_itoa(d, str, 10);
        string tostr(str);

        return tostr;
    }
};


看看别人写的代码:

class Solution {
public:
    string addBinary(string a, string b) {
     string longStr = a.length() > b.length() ? a : b;
     string shortStr = a.length() > b.length() ? b : a;
 
     int ad = 0;
     int j = longStr.length() - 1;
 
     for(int i = shortStr.length() - 1; i > -1; i--, j--) {
         if(shortStr[i] - '0' + longStr[j] - '0' + ad > 1) {
             longStr[j] = '0' + (shortStr[i] - '0' + longStr[j] - '0' + ad) % 2;
             ad = 1;
         }
         else {
             longStr[j] = '0' + shortStr[i] - '0' + longStr[j] - '0' + ad;
             ad = 0;
         }
     }
 
     for(; j > -1; j--) {
         if(longStr[j] - '0' + ad > 1) {
             longStr[j] = '0' + (longStr[j] -'0' + ad) % 2;
             ad = 1;
         }
         else {
             longStr[j] = '0' + (longStr[j] - '0' + ad) % 2;
             ad = 0;
         }
     }
 
     if(ad) {
         longStr.insert(0,1,'1');
     }
 
     return longStr;
    }
};
自己对string的操作太不熟悉了 再见差距~~~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值