当前位置:网站首页>Binary sum of leetcode questions
Binary sum of leetcode questions
2022-04-23 06:53:00 【zjLOVEcyj】
Binary sum
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”
Tips :
Each string consists only of characters ‘0’ or ‘1’ form .
1 <= a.length, b.length <= 10^4
If the string is not “0” , No leading zeros .
var addBinary = function(a, b) {
let a_length = a.length
let b_length = b.length
let res = []
if (a_length > b_length) {
b = b.padStart(a_length, '0')
b_length = a_length
} else if (a_length < b_length) {
a = a.padStart(b_length, '0')
a_length = b_length
}
let temp = 0
for (let k = a_length - 1; k >= 0; k--) {
let temp_sum = temp + parseInt(a[k]) + parseInt(b[k])
let end_sum = 0
if (temp_sum === 0) {
end_sum = 0
temp = 0
} else if (temp_sum === 1) {
end_sum = 1
temp = 0
} else if (temp_sum === 2) {
end_sum = 0
temp = 1
} else if (temp_sum === 3) {
end_sum = 1
temp = 1
}
res.unshift(end_sum)
}
if (temp === 1) {
res.unshift(1)
}
return res.join('')
}
let a = "1", b = "111"
res = addBinary(a, b)
console.log(res);
版权声明
本文为[zjLOVEcyj]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230555333801.html
边栏推荐
猜你喜欢
随机推荐
Centos8 builds php8 0.3 operating environment
el-cascader和el-select点击别处让下拉框消失
useCenterHook
China creates vast research infrastructure to support ambitious climate goals
thinkphp5 ---- object(think\response\Json)转数组
不用登录直接下载PNG图标的一个网站
DNA reveals surprise ancestry of mysterious Chinese mummies
PHP background parsing after JQ serialization
数据可视化进一步学习
WebSocket(基础)
tp5 报错variable type error: array解决方法
百度地图3D旋转和倾斜角度的调整
1-1 NodeJS
【代码解析(6)】Communication-Efficient Learning of Deep Networks from Decentralized Data
mysql中sum (if)_mysql 中sum (if())
ASP.NET CORE JWT认证
Router对象、Route对象、声明式导航、编程式导航
fdfs启动
SignalR实现从服务端主动发送数据到客户端
出入库与库存系统的模型问题