• 【leetcode】Add Binary


    Add Binary 

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

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

    Hide Tags
      Math String
     
     
    先补全字符串,从末尾开始加,每次计算当前位和进位即可
     1 class Solution {
     2 public:
     3     char addBit(char a,char b,char &c)
     4     {
     5         if(a==b&&a=='1')
     6         {
     7             char ret;
     8             ret=c;
     9             c='1';
    10             return ret;
    11         }
    12         else if(a==b&&a=='0')
    13         {
    14             
    15             if(c=='0')
    16             {
    17                 return '0';
    18             }
    19             else
    20             {
    21                 c='0';
    22                 return '1';
    23             }
    24         }
    25         else
    26         {
    27             if(c=='1')
    28                return '0';
    29             else
    30                return '1';
    31             
    32         }
    33     }
    34     
    35     string addBinary(string a, string b) {
    36         
    37         int na=a.length()-1;
    38         int nb=b.length()-1;
    39         
    40         if(na!=nb)
    41         {
    42             string tmp(abs(na-nb),'0');
    43             if(na>nb)
    44                 b=tmp+b;
    45             else
    46                 a=tmp+a;
    47         }
    48         
    49         int i=a.length()-1;
    50         string result(a.length(), '1');
    51         char c='0';
    52         
    53         while(i>=0)
    54         {
    55             result[i]=addBit(a[i],b[i],c);
    56             i--;
    57         }
    58         if(c=='0')
    59         {
    60             return result;
    61         }
    62         else
    63         {
    64             return '1'+result;
    65         }
    66     }
    67 };
  • 相关阅读:
    function函数
    for的衍生对象
    前端发展史
    字符串替换
    正则
    DOM和BOM的区别与联系
    BOM
    DOM
    css单位分析
    API and Web API
  • 原文地址:https://www.cnblogs.com/reachteam/p/4251647.html
Copyright © 2020-2023  润新知