当前位置:网站首页>[算法] 剑指offer2 golang 面试题2:二进制加法
[算法] 剑指offer2 golang 面试题2:二进制加法
2022-07-06 09:18:00 【邓嘉文Jarvan】
[算法] 剑指offer2 golang 面试题2:二进制加法
题目1:
给定两个 01 字符串 a 和 b ,请计算它们的和,并以二进制字符串的形式输出。
输入为 非空 字符串且只包含数字 1 和 0。
示例 1:
输入: a = “11”, b = “10”
输出: “101”
示例 2:
输入: a = “1010”, b = “1011”
输出: “10101”
提示:
每个字符串仅由字符 ‘0’ 或 ‘1’ 组成。
1 <= a.length, b.length <= 10^4
字符串如果不是 “0” ,就都不含前导零。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/JFETK5
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路1: 模拟二进制加法
模拟二进制加法时间复杂度 O(n)
代码
func addBinary(a string, b string) string {
//思路: 模拟二进制计算
length := len(a)
if len(b) > len(a) {
length = len(b)
}
//构造返回
resBs := make([]byte, length)
//从后往前指向的指针
aP, bP := len(a)-1, len(b)-1
//是否进位
up := 0
for i := len(resBs) - 1; i >= 0; i-- {
var aByte byte = '0'
var bByte byte = '0'
if aP >= 0 {
aByte = a[aP]
aP--
}
if bP >= 0 {
bByte = b[bP]
bP--
}
// 统计个数
count1 := 0
if aByte == '1' {
count1++
}
if bByte == '1' {
count1++
}
count1 += up
//通过个数确定当前值和up
if count1 == 0 {
up = 0
resBs[i] = '0'
} else if count1 == 1 {
up = 0
resBs[i] = '1'
} else if count1 == 2 {
up = 1
resBs[i] = '0'
} else {
up = 1
resBs[i] = '1'
}
}
//最后的up
res := string(resBs)
if up == 1 {
res = "1" + res
}
return res
}
测试
边栏推荐
- FairyGUI复选框与进度条的组合使用
- Combination of fairygui check box and progress bar
- rtklib单点定位spp使用抗差估计遇到的问题及解决
- [leetcode622] design circular queue
- [899]有序队列
- FairyGUI按钮动效的混用
- 【GNSS】抗差估计(稳健估计)原理及程序实现
- 1041 Be Unique (20 point(s))(哈希:找第一个出现一次的数)
- Unity3d, Alibaba cloud server, platform configuration
- Database course design: college educational administration management system (including code)
猜你喜欢
Unity3d, Alibaba cloud server, platform configuration
2021.11.10 compilation examination
NovAtel 板卡OEM617D配置步骤记录
RTKLIB: demo5 b34f.1 vs b33
Unity场景跳转及退出
Prove the time complexity of heap sorting
Mixed use of fairygui button dynamics
Unity scene jump and exit
Naive Bayesian theory derivation
Esp8266 connect onenet (old mqtt mode)
随机推荐
FairyGUI增益BUFF數值改變的顯示
(课设第一套)1-4 消息传递接口 (100 分)(模拟:线程)
It has been solved by personal practice: MySQL row size too large (> 8126) Changing some columns to TEXT or BLOB or using ROW_ FORMAT
Remember an experience of ECS being blown up by passwords - closing a small black house, changing passwords, and changing ports
Get the position of the nth occurrence of the string
MySQL replacement field part content
About using @controller in gateway
KF UD分解之UD分解基础篇【1】
How to improve the deletion speed of sequential class containers?
GNSS定位精度指标计算
What are the functions and features of helm or terrain
第一人称视角的角色移动
FairyGUI简单背包的制作
NRF24L01故障排查
JUC forkjoin and completable future
SSD technical features
Design and implementation of general interface open platform - (39) simple and crude implementation of API services
wsl常用命令
ORA-02030: can only select from fixed tables/views
idea中导包方法