• [LeetCode]Add Binary


    给定字符串a,b,分别表示两个二进制数。将a,b的二进制和以字符串形式返回。

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

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

    思路:模拟二进制加法过程,从最低位开始

    难点在于进位的计算。记进位符为carry, 该位的和为num

    int num = a[i]-'0'+b[j]-'0'+carry;
    carry = num/2;
    num %= 2;

    代码

     1 class Solution {
     2 public:
     3     string addBinary(string a, string b) {
     4         // IMPORTANT: Please reset any member data you declared, as
     5         // the same Solution instance will be reused for each test case.
     6         string ret;
     7         int i=a.length()-1, j=b.length()-1;
     8         int carry = 0;
     9         while(i>=0 && j>=0)
    10         {
    11             int num = a[i]-'0'+b[j]-'0'+carry;
    12             carry = num/2;
    13             num %= 2;
    14             ret = char(num+'0') + ret;
    15             --i; --j;
    16         }
    17         // add carry and remaining string
    18         while(i>=0)
    19         {
    20             int num = a[i]-'0'+carry;
    21             carry = num/2;
    22             num %=2;
    23             ret = char(num+'0')+ret;
    24             --i;
    25         }
    26         while(j>=0)
    27         {
    28             int num = b[j]-'0'+carry;
    29             carry = num/2;
    30             num %=2;
    31             ret = char(num+'0')+ret;
    32             --j;
    33         }
    34         
    35         if(carry>0)
    36             ret = "1"+ret;
    37         
    38         return ret;
    39     }
    40 };
  • 相关阅读:
    vue分页组件(二)
    ES6里let、const、var区别总结
    electron-vue项目打包踩坑记录
    node环境变量配置
    第一次把本地项目与git相连
    java项目环境搭建
    npm上发布vue插件
    HTML5日期时间输入类型注意事项(time,date)
    vue 分页组件
    vue里ref ($refs)用法
  • 原文地址:https://www.cnblogs.com/practice/p/3392236.html
Copyright © 2020-2023  润新知