【LeetCode with Python】 Add Binary
来源:互联网 发布:java编程思想是什么 编辑:程序博客网 时间:2024/05/01 16:48
博客域名:http://www.xnerv.wang
原题页面:https://oj.leetcode.com/problems/add-binary/
题目类型:模拟运算
难度评价:★
本文地址:http://blog.csdn.net/nerv3x3/article/details/4137815
原题页面:https://oj.leetcode.com/problems/add-binary/
题目类型:模拟运算
难度评价:★
本文地址:http://blog.csdn.net/nerv3x3/article/details/4137815
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
用字符串模拟二进制整数加法。写了一个更通用的算法,修改self.radix即可将代码改为如八进制整数加法、十进制整数加法等。
class Solution: def __init__(self): self.radix = 2 # @param a, a string # @param b, a string # @return a string def addBinary(self, a, b): a_nums = [(ord(ch) - ord('0')) for ch in a] b_nums = [(ord(ch) - ord('0')) for ch in b] a_nums_size = len(a_nums) b_nums_size = len(b_nums) max_nums_size = max(a_nums_size, b_nums_size) a_extend_nums = [0 for i in range(0, max_nums_size - a_nums_size)] b_extend_nums = [0 for i in range(0, max_nums_size - b_nums_size)] a_nums = a_extend_nums + a_nums b_nums = b_extend_nums + b_nums sum_nums = [0] * max_nums_size carry = 0 for i in range(max_nums_size - 1, -1, -1): sum = a_nums[i] + b_nums[i] + carry sum_nums[i] = sum % self.radix carry = sum / self.radix sum_str = ("1" if 1 == carry else "") for i in range(0, max_nums_size): sum_str += chr(sum_nums[i] + ord('0')) return sum_str
- 【LeetCode with Python】 Add Binary
- 【Leetcode】【python】Add Binary
- 67. Add Binary Leetcode Python
- leetcode Add Binary python 题解
- [leetcode:python]67.Add Binary
- Python学习——leetcode(Add Binary)
- 【leetcode】67. Add Binary(Python & C++)
- 【LeetCode with Python】 Add Two Numbers
- 【LeetCode with Python】 Validate Binary Search Tree
- 【LeetCode with Python】 Binary Tree Preorder Traversal
- 【LeetCode with Python】 Binary Tree Inorder Traversal
- 【LeetCode with Python】 Balanced Binary Tree
- 【LeetCode with Python】 Unique Binary Search Trees
- LeetCode: Add Binary
- [Leetcode] Add Binary
- LeetCode Add Binary
- Leetcode: Add Binary
- [Leetcode] Add Binary
- 一次一密乱码本
- 金属探测器
- AES
- 一对多联合查询用exist代替distinct的句子
- SQL2000 安装
- 【LeetCode with Python】 Add Binary
- C#拖动文件到窗体上如何限制类型只能是图片类型(急求)
- 数据仓库成熟度模型
- 程序MFC71D.DLL 找不到
- Linux内核之—内核链表二
- PP-PP和其他模块的集成
- Developer Express 中的 WPF 资源总结
- 开题
- InstallShield 2009制作集成.NET Framework 2.0 Service Pack 2的安装包