当前位置:网站首页>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
边栏推荐
猜你喜欢
随机推荐
自用学习笔记-连接式与非连接式访问数据库
NodeJS 模块之间的使用
浏览器中堆栈内存的底层处理
New formdata() when importing files
Each traversal usage of tp6
PHP background parsing after JQ serialization
浏览器工作原理与实践
1-3 组件与模块
js中entries(),keys(),values() , some(), Object.assign()遍历数组用法
leetcode刷题之整数加一
百度地图3D旋转和倾斜角度的调整
Method of MySQL password expiration
Router对象、Route对象、声明式导航、编程式导航
关于软件的空间占用,安装目录
时间格式不对,运行sql文件报错
Node模版引擎(ejs, art-template)
SiteServer CMS5.0使用总结
最近编程中遇到的一些问题2021/9/8
百度地图案例-修改地图样式
JS性能优化