zoukankan      html  css  js  c++  java
  • [LeetCode]Add Binary

    题目描述:

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

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

    解题方案:

     1 class Solution {
     2 public:
     3     string addBinary(string a, string b) {
     4         int LocationA = a.size() - 1;
     5         int LocationB = b.size() - 1;
     6 
     7         if (LocationA == -1) {
     8             return b;
     9         }
    10         if (LocationB == -1) {
    11             return a;
    12         }
    13         string result;
    14         int carry = 0;
    15 
    16         while((LocationA >= 0) && (LocationB >= 0)) {
    17             int temp = ((a[LocationA] - '0') + (b[LocationB] - '0') + carry) % 2;
    18             carry    = ((a[LocationA] - '0') + (b[LocationB] - '0') + carry) / 2;
    19             result.append(1, temp + '0');
    20             --LocationA;
    21             --LocationB;
    22         }
    23         if (LocationA != -1) {
    24             while(LocationA >= 0) {
    25                 int temp = ((a[LocationA] - '0') + carry) % 2;
    26                 carry    = ((a[LocationA] - '0') + carry) / 2;
    27                 result.append(1, temp + '0');
    28                 --LocationA;
    29             }
    30         }
    31         if (LocationB != -1) {
    32             while(LocationB >= 0) {
    33                 int temp = ((b[LocationB] - '0') + carry) % 2;
    34                 carry    = ((b[LocationB] - '0') + carry) / 2;
    35                 result.append(1, temp + '0');
    36                 --LocationB;
    37             }
    38         }
    39 
    40         if (carry != 0) {
    41             result.append(1, carry + '0');
    42         }
    43 
    44         int i = 0;
    45         int j = result.size() - 1;
    46         //将字符串反转
    47         while (i <= j) {
    48             char temp = result[i];
    49             result[i] = result[j];
    50             result[j] = temp;
    51             ++i;
    52             --j;
    53         }
    54         return result;
    55     }
    56 };
  • 相关阅读:
    Elasticsearch 快速入门
    Linux 非互联网环境安装依赖包
    linux 安装mysql(rpm文件安装)
    Nginx安装与配置文件nginx.conf详解
    Linux 知识
    MySQL Windows安装连接
    post请求body格式
    MySQL 数据库备份
    SOAP与restful webservice
    大数据架构工具hadoop
  • 原文地址:https://www.cnblogs.com/skycore/p/4032593.html
Copyright © 2011-2022 走看看