当前位置:网站首页>[算法] 剑指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
}
测试
边栏推荐
- Easy to use shortcut keys in idea
- What is the maximum length of MySQL varchar field
- [Chongqing Guangdong education] reference materials for regional analysis and planning of Pingdingshan University
- 【GNSS数据处理】赫尔默特(helmert)方差分量估计解析及代码实现
- Minio file download problem - inputstream:closed
- [899]有序队列
- (课设第一套)1-4 消息传递接口 (100 分)(模拟:线程)
- The service robots that have been hyped by capital and the Winter Olympics are not just a flash in the pan
- Prove the time complexity of heap sorting
- [Nodejs] 20. Koa2 onion ring model ----- code demonstration
猜你喜欢
随机推荐
The service robots that have been hyped by capital and the Winter Olympics are not just a flash in the pan
FairyGUI按钮动效的混用
Matlab读取GNSS 观测值o文件代码示例
Fairygui character status Popup
1041 be unique (20 points (s)) (hash: find the first number that occurs once)
(core focus of software engineering review) Chapter V detailed design exercises
[offer29] sorted circular linked list
Meanings and differences of PV, UV, IP, VV, CV
By v$rman_ backup_ job_ Oracle "bug" caused by details
服务未正常关闭导致端口被占用
[offer9]用两个栈实现队列
Fabrication of fairygui simple Backpack
Compile GDAL source code with nmake (win10, vs2022)
SSD technical features
Get the position of the nth occurrence of the string
Expected value (EV)
FairyGUI循環列錶
[Chongqing Guangdong education] reference materials for regional analysis and planning of Pingdingshan University
wsl常用命令
@The difference between Autowired and @resource