我是靠谱客的博主 整齐小丸子,这篇文章主要介绍[Leetcode]二进制求和,现在分享给大家,希望可以做个参考。

[Leetcode]二进制求和

Leetcode-二进制求和

题目描述

给你两个二进制字符串,返回它们的和(用二进制表示)。
输入为 非空 字符串且只包含数字 1 和 0。

示例 1:
输入: a = “11”, b = “1”
输出: “100”

示例 2:
输入: a = “1010”, b = “1011”
输出: “10101”

提示:
每个字符串仅由字符 ‘0’ 或 ‘1’ 组成。
1 <= a.length, b.length <= 10^4
字符串如果不是 “0” ,就都不含前导零。

实现代码
  • Python - 转十进制
复制代码
1
2
3
4
class Solution: def addBinary(self, a: str, b: str) -> str: return '{0:b}'.format(int(a, 2) + int(b, 2))
  • C++ - 模拟加法
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution { public: string addBinary(string a, string b) { int lena = a.length(); int lenb = b.length(); string res; int carry = 0; for (int i = lena - 1, j = lenb - 1; i >= 0 || j >= 0; i--, j--){ carry += i>=0 ? a[i] - '0' : 0; carry += j>=0 ? b[j] - '0' : 0; res.push_back(carry % 2 + '0'); carry /= 2; } if (carry != 0) res.push_back('1'); reverse(res.begin(), res.end()); //结果需要反转 return res; } };

最后

以上就是整齐小丸子最近收集整理的关于[Leetcode]二进制求和的全部内容,更多相关[Leetcode]二进制求和内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(99)

评论列表共有 0 条评论

立即
投稿
返回
顶部