zoukankan      html  css  js  c++  java
  • leetcode

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

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

    字符串相加,不难

    个人思路:

    1,尾部对齐,然后逐位相加,flag记为进位

    代码:

     1 #include <string>
     2 
     3 using namespace std;
     4 
     5 class Solution {
     6 public:
     7     string addBinary(string a, string b) {
     8         if (a.empty())
     9         {
    10             return b;
    11         }
    12         if (b.empty())
    13         {
    14             return a;
    15         }
    16 
    17         int aLen = a.length();
    18         int bLen = b.length();
    19         int i = aLen - 1, j = bLen - 1;
    20         int flag = 0; //进位
    21         int temp, ai, bj;
    22         string result;
    23 
    24         for (; i >= 0 || j >= 0; --i, --j)
    25         {
    26             ai = i >= 0 ? (a[i] - '0') : 0;
    27             bj = j >= 0 ? (b[j] - '0') : 0;
    28 
    29             temp = ai + bj + flag;
    30             flag = temp > 1 ? 1 : 0;
    31             temp = temp - flag * 2;
    32 
    33             result.insert(result.begin(), temp + '0');
    34         }
    35 
    36         if (flag)
    37         {
    38             result.insert(result.begin(), '1');
    39         }
    40 
    41         return result;
    42     }
    43 };
    View Code
  • 相关阅读:
    pandas isin 和not in
    游戏开发需要学什么?
    打开页面,数字会自增的效果怎么弄?
    jq 导航栏点击添加/删除类(a标签跳转页面)
    bootstrap+jq分页
    2020/12/18
    2020/12/17
    2020/12/16
    2020/12/15
    2020/12/14
  • 原文地址:https://www.cnblogs.com/laihaiteng/p/3962382.html
Copyright © 2011-2022 走看看