zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):067-Add Binary

    题目来源:

      https://leetcode.com/problems/add-binary/


    题意分析:

      这题是要将二进制相加,比如“11”,“1”,那么就返回“100”。


    题目思路:

      模拟加法的过程,直接模拟,大于等于2就进位。


    代码(Python):

      

     1 class Solution(object):
     2     def addBinary(self, a, b):
     3         """
     4         :type a: str
     5         :type b: str
     6         :rtype: str
     7         """
     8         size1 = len(a);size2 = len(b)
     9         if size1 == 0:
    10             return b
    11         if size2 == 0:
    12             return a
    13         carry,ans = 0,""
    14         while size1 > 0 and size2 > 0:
    15             tmp = int(a[size1 -1]) + int(b[size2 - 1]) + carry
    16             carry = tmp // 2;tmp %= 2
    17             ans += str(tmp)
    18             size1 -= 1;size2 -= 1
    19         if size1 == 0:
    20             while size2 > 0:
    21                 tmp = int(b[size2 - 1]) + carry
    22                 carry = tmp // 2;tmp %= 2
    23                 ans += str(tmp)
    24                 size2 -= 1
    25         if size2 == 0:
    26             while size1 > 0:
    27                 tmp = int(a[size1 - 1]) + carry
    28                 carry = tmp // 2;tmp %= 2
    29                 ans += str(tmp)
    30                 size1 -= 1
    31         if carry == 1:
    32             ans += str(carry)
    33         ans = ans[::-1]
    34         return ans
    View Code

    转载请注明出处:http://www.cnblogs.com/chruny/p/5028769.html

  • 相关阅读:
    快排 [模板]
    翻硬币
    Euphoria与量子波动速读
    高精度例题
    Div3 595 E
    Div 595 C1 C2
    常用 STL 整理
    CF 595 Div3 B2
    【思维】复杂度均摊+并查集——icpc cerc 2019 Saba1000kg
    离散化+圆直线交点+转化——icpc cerc 2019 D
  • 原文地址:https://www.cnblogs.com/chruny/p/5028769.html
Copyright © 2011-2022 走看看