zoukankan      html  css  js  c++  java
  • LeetCode

    Add Binary

    2013.12.22 03:31

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

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

    Solution:

      This is a problem about big integer addition, only in that it's binary. My solution is to add them up bit by bit, reverse the char array and return the result as std::string.

      Time compexity is O(max(m, n)), space complexity is O(max(m, n)), where m and n are the length of two strings.

    Accepted code:

     1 #define __MAIN__
     2 #ifdef __MAIN__
     3 #include <string>
     4 using namespace std;
     5 #endif
     6 
     7 class Solution {
     8 public:
     9     string addBinary(string a, string b) {
    10         // Note: The Solution object is instantiated only once and is reused by each test case.
    11         if(a.length() < b.length()){
    12             return addBinary(b, a);
    13         }
    14         
    15         if(a == "0"){
    16             return b;
    17         }else if(b == "0"){
    18             return a;
    19         }
    20         
    21         int i;
    22         char *buf = nullptr, tmp;
    23         int lena, lenb;
    24         
    25         lena = a.length();
    26         lenb = b.length();
    27         buf = new char[lena + 2];
    28         for(i = 0; i < lena + 2; ++i){
    29             buf[i] = 0;
    30         }
    31         for(i = 0; i < lena; ++i){
    32             buf[i] += (a[lena - 1 - i] - '0');
    33         }
    34         for(i = 0; i < lenb; ++i){
    35             buf[i] += (b[lenb - 1 - i] - '0');
    36         }
    37         for(i = 0; i < lena + 1; ++i){
    38             buf[i + 1] += buf[i] / 2;
    39             buf[i] %= 2;
    40         }
    41         for(i = 0; i < lena + 1; ++i){
    42             buf[i] += '0';
    43         }
    44         for(i = 0; i < lena - i; ++i){
    45             tmp = buf[i];
    46             buf[i] = buf[lena - i];
    47             buf[lena - i] = tmp;
    48         }
    49         
    50         string res;
    51         if(buf[0] > '0'){
    52             res = string(buf);
    53         }else{
    54             res = string(buf + 1);
    55         }
    56         delete[] buf;
    57         
    58         return res;
    59     }
    60 };
  • 相关阅读:
    2019 SDN第二次上机作业
    2019 SDN上机第1次作业
    第五次软工作业结对编程
    JIRA中的核心概念
    产品经理与项目经理的区别
    掀起你的盖头来:浅谈项目管理办公室(PMO)
    你大概走了假敏捷:认真说说敏捷的实现和问题(手绘版)
    项目管理经验
    项目经理面试中可能遇到的问题
    回到网易8个月测试团队转型实践
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3485742.html
Copyright © 2011-2022 走看看