LeetCode Add Binary (JavaScript)
来源:互联网 发布:mac book 手写便签 编辑:程序博客网 时间:2024/06/07 06:06
题目:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
思路:
反序遍历字符串,并判断是否有进位。
代码如下
var addBinary = function(a, b) { var alen = a.length; var blen = b.length; if(alen === 0){ return b; }else if(blen === 0){ return a; } //将a、b变成等长的字符串 if(alen>blen){ for(var i=0;i<alen-blen;i++){ b = "0"+b; } blen = b.length; }else if(alen<blen){ for(i=0;i<blen-alen;i++){ a = "0" + a; } alen = a.length; } var c; var carry = 0; //进位判断 var result = []; var len = alen -1; while(len > -1){ c = parseInt(a.charAt(len)) + parseInt(b.charAt(len)) + carry; carry = parseInt(c/2); if(c%2){ result.unshift("1"); }else{ result.unshift("0"); } len--; } if(carry == 1){ result.unshift("1"); } result = result.join(""); //将数组转换成字符串 return result;};
0 0
- LeetCode Add Binary (JavaScript)
- LeetCode: Add Binary
- [Leetcode] Add Binary
- LeetCode Add Binary
- Leetcode: Add Binary
- [Leetcode] Add Binary
- LeetCode : Add Binary
- LeetCode Add Binary
- [LeetCode] Add Binary
- leetcode 58: Add Binary
- leetcode Add Binary
- [LeetCode] Add Binary
- 【leetcode】Add Binary
- [LeetCode]Add Binary
- [leetcode]Add Binary
- LeetCode-Add Binary
- [leetcode] Add Binary
- LeetCode - Add Binary
- ps把图片背景变透明
- 蛇形(回形)矩阵
- c2d libgdx 封装
- generate html code from QTableWidget with row and column span support
- itunes里面的设备栏里没应用程序选项
- LeetCode Add Binary (JavaScript)
- Oracle replace 函数用法 alisa问题记录1
- Permission denied:Android导出shared_prefs中xml文件时出错
- jdk配置环境变量
- Android WebView从assets中加载html5页面,实现地理位置定位
- Android传感器概述(五)
- IE中居中,FF中出问题
- 一篇能很好反映普通接口多态 工厂模式 依赖注入三者的耦合强度区别的文章
- Intersection of Two Linked Lists(有优化)