当前位置:网站首页>Leetcode-67. binary sum
Leetcode-67. binary sum
2022-07-23 16:52:00 【KGundam】
Mathematical problems
Topic details
Here are two binary strings , Returns the sum of them ( In binary ).
Input is Non empty String and contains only numbers 1 and 0.
Example 1:
Input : a = "11", b = "1"
Output : "100"
Example 2:
Input : a = "1010", b = "1011"
Output : "10101"
Ideas :
The question is leetcode-415. Variant of string addition , It's just that decimal has become binary , The idea is exactly the same
my 415 Detailed analysis of the problem solution :
leetcode-415. String addition
My code :
class Solution
{
public:
string addBinary(string a, string b)
{
string res = ""; // Save the result
// Turn it around
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int len_a = a.length(), len_b = b.length();
if (len_a <= len_b) // Let the longer number come first
{
swap(a, b);
swap(len_a, len_b);
}
int addbit = 0; // Carry or not
for (int i = 0; i < len_b; ++i) // Deal with equal length parts
{
int cur_sum = (a[i] - '0') + (b[i] - '0') + addbit;
res += to_string(cur_sum % 2);
addbit = cur_sum < 2? 0 : 1;
}
for (int i = len_b; i < len_a; ++i) // Handle longer parts
{
int cur_sum = (a[i] - '0') + addbit;
res += to_string(cur_sum % 2);
addbit = cur_sum < 2? 0 : 1;
}
if (addbit) // Process the highest bit
{
res += "1";
}
reverse(res.begin(), res.end()); // Turn back
return res;
}
};
边栏推荐
- Nifi 1.16.3 集群搭建+kerberos+用户认证
- Surface family purchase reference
- Hcip datacom certification examination passed in July
- 【C语言】结构体、枚举和联合体
- pytest接口自动化测试框架 | pytest常用运行参数
- Squeeze-and-Excitation Networks(挤压和激励网络)
- 百度编辑器上传图片设置自定义目录
- ESP8266-NodeMCU——从苏宁API获取实时天气
- tensorflow2.X实战系列softmax函数
- COPU副主席刘澎:中国开源在局部领域已接近或达到世界先进水平
猜你喜欢
随机推荐
2022-7-22 面经复习+简单题目整理
动态规划背包问题之多重背包详解
【笔记】线性回归
泰山OFFICE技术讲座:段落边框的布局绘制分析
go语言的基础语法(变量、常量、基本数据类型,for、switch,case、数组、slice(切片)、make和new、map)
UiPath Studio Enterprise 22.4 Crack
Scale Match for Tiny Person Detection
Navicat15下载安装
【C语言】结构体、枚举和联合体
Nifi 1.16.3 cluster setup +kerberos+ user authentication
Less than 10 days before the PMP Exam on July 30, what should be done?
熵权法优化TOPSIS(MATLAB)
Cuibaoqiu, vice president of Xiaomi group: open source is the best platform and model for human technological progress
mysql的常见问题
CNCF基金会总经理Priyanka Sharma:一文读懂CNCF运作机制
卷积神经网络模型之——GoogLeNet网络结构与代码实现
fastadmin,非超级管理员,已赋予批量更新权限,仍显示无权限
[2022 freshmen learning] key points of the second week
单片机内部IO口保护电路及IO口电气特性以及为什么不同电压IO之间为什么串联一个电阻?
Tan Zhangxi, director of risc-v Foundation: risc-v has gradually expanded from the edge to the center







