• LeetCode Add Binary


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

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

    这题用数组来做可能更简单,但考虑到可能面试的时候要求不能开额外的数组,就只能对string操作了。最主要的是把进位这部分写对。

     1 class Solution {
     2 public:
     3     string addBinary(string a, string b) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         int flag = 0;
     7         
     8         int aIndex = a.size() - 1;
     9         int bIndex = b.size() - 1;
    10         
    11         string c;
    12         
    13         while(aIndex >= 0 && bIndex >= 0)
    14         {
    15             int num = a[aIndex] - '0' + (b[bIndex] - '0') + flag;
    16             flag = num / 2;
    17             num %= 2;
    18             
    19             c = (char)(num + '0') + c;
    20             
    21             aIndex--;
    22             bIndex--;
    23         }
    24         
    25         while(aIndex >= 0)
    26         {
    27             int num = a[aIndex] - '0' + flag;
    28             flag = num / 2;
    29             num %= 2;
    30             
    31             c = (char)(num + '0') + c;
    32             
    33             aIndex--;
    34         }
    35         
    36         while(bIndex >= 0)
    37         {
    38             int num = b[bIndex] - '0' + flag;
    39             flag = num / 2;
    40             num %= 2;
    41             
    42             c = (char)(num + '0') + c;
    43             
    44             bIndex--;
    45         }
    46         
    47         if (flag > 0)
    48             c = (char)(flag + '0') + c;
    49             
    50         return c;
    51     }
    52 };
  • 相关阅读:
    判断DataSet为空
    msxml3.dll 错误 '800c0008'
    google Map api地理位置坐标转换
    C# .net中cookie值为中文时的乱码解决方法
    windows pear 安装
    smarty2 设置、变量、函数
    简单模板类
    mysql 1366 插入错误
    Oracle修改账户口令
    C# Winform验证码
  • 原文地址:https://www.cnblogs.com/chkkch/p/2742717.html
Copyright © 2020-2023  润新知