当前位置:网站首页>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
边栏推荐
猜你喜欢
随机推荐
【代码解析(5)】Communication-Efficient Learning of Deep Networks from Decentralized Data
freeCodeCamp----budget & category 练习
1-2 NodeJS的特点
条形码与二维码的生成
.NET跨平台原理(上篇)
JS实现模态框拖拽
浏览器工作原理与实践
Leak detection and filling (I)
New features of ES6
元编程,代理Proxy与反射Reflect
ASP.NET CORE 配置选项(上篇)
关于注解1
微信小程序
【Markdown笔记】
ASP.NET CORE3.1 Identity注册用户后登录失败的解决方案
Leak detection and vacancy filling (III)
Decentralized Collaborative Learning Framework for Next POI Recommendation
leetcode刷题之x的算术平方根
Node模版引擎(ejs, art-template)
数据可视化进一步学习









