Skip to content

Instantly share code, notes, and snippets.

@zmofei
Created April 21, 2016 02:44
Show Gist options
  • Save zmofei/b97994ccf8084ddf3bd0bac52e82a52b to your computer and use it in GitHub Desktop.
Save zmofei/b97994ccf8084ddf3bd0bac52e82a52b to your computer and use it in GitHub Desktop.
最前端:2016年4月20日,智力题题目解决方案
function add(a, b) {
var res = '',
c = 0
a = a.split('')
b = b.split('')
while (a.length || b.length || c) {
c += ~~a.pop() + ~~b.pop()
res = c % 10 + res
c = c > 9
}
return res
}
// 点评:
// 巧妙地运用了按位非运算 (~a 反转操作数的比特位,即0变成1,1变成0。)
// 位运算 NOT 是三步的处理过程:
// 1. 把运算数转换成 32 位数字
// 2. 把二进制数转换成它的二进制反码(0->1, 1->0)
// 3. 把二进制数转换成浮点数
// * 简单的可以理解成 -(x + 1)
//
// 按位非的应用:
// 1.
// 判断数值中是否有某元素时,以前这样判断:
// if(arr.indexOf(ele) > -1){...} //易读
// 现在可以这样判断,两者效率:
// if(~arr.indexOf(ele)){...} //简洁
// 2.
// ~~value替代parseInt(value),效率更高
// parseInt(-24.79) //-24
// ~~(-24.79) //-24
// 3. ~~undefined 等初始化默认值为0
// 本例中的 ~~a.pop() 巧妙地取代了 a.pop()||0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment