当前位置:网站首页>[算法] 劍指offer2 golang 面試題2:二進制加法
[算法] 劍指offer2 golang 面試題2:二進制加法
2022-07-06 12:50: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
}
測試
边栏推荐
- Intermediate use tutorial of postman [environment variables, test scripts, assertions, interface documents, etc.]
- idea问题记录
- [Leetcode15]三数之和
- Compile GDAL source code with nmake (win10, vs2022)
- Office提示您的许可证不是正版弹框解决
- NovAtel 板卡OEM617D配置步骤记录
- 【GNSS数据处理】赫尔默特(helmert)方差分量估计解析及代码实现
- Unity3d makes the registration login interface and realizes the scene jump
- How to reduce the shutdown time of InnoDB database?
- 基于rtklib源码进行片上移植的思路分享
猜你喜欢
随机推荐
idea问题记录
Fairygui gain buff value change display
基本Dos命令
[offer29] sorted circular linked list
Particle system for introduction to unity3d Foundation (attribute introduction + case production of flame particle system)
(the first set of course design) sub task 1-5 317 (100 points) (dijkstra: heavy edge self loop)
Unity scene jump and exit
Conditional probability
1041 Be Unique (20 point(s))(哈希:找第一个出现一次的数)
Solution to the problem of automatic login in Yanshan University Campus Network
Knowledge system of digital IT practitioners | software development methods -- agile
FairyGUI簡單背包的制作
Mysql database index
FairyGUI增益BUFF数值改变的显示
By v$rman_ backup_ job_ Oracle "bug" caused by details
(课设第一套)1-4 消息传递接口 (100 分)(模拟:线程)
【rtklib】在rtk下使用抗差自适应卡尔曼滤波初步实践
What are the functions and features of helm or terrain
FairyGUI简单背包的制作
[leetcode622] design circular queue