zoukankan      html  css  js  c++  java
  • Add Binary

    Given two binary strings, return their sum (also a binary string).
    For example,
    a = "11"
    b = "1"
    Return "100".

    Solution: '1'-'0' = 1.

     1 class Solution {
     2 public:
     3     string addBinary(string a, string b) {
     4         int N = a.size();
     5         int M = b.size();
     6         int K = max(M, N);
     7         string res(K,' ');
     8         int carry = 0;
     9         int i = N - 1, j = M - 1, k = K - 1;
    10         while(i >= 0 || j >= 0) {
    11             int sum = carry;
    12             if(i >= 0) sum += a[i--] - '0';
    13             if(j >= 0) sum += b[j--] - '0';
    14             carry = sum / 2;
    15             res[k--] = sum % 2 + '0'; 
    16         }
    17         if(carry == 1) res.insert(res.begin(), '1');
    18         return res;
    19     }
    20 };
  • 相关阅读:
    jq insertBefore 的返回值
    微信公众号-定位之地址逆解析&导航
    微信JS-SDK
    Vue
    ES6-函数的扩展
    ES6-数组的扩展
    JSP
    JS
    HTML+CSS
    jdbc操作数据库
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3665974.html
Copyright © 2011-2022 走看看