js double bitwise not ~~ All In One
js 双非位运算
~~
0
vs NaN
const arr = [];
// []
~~arr.pop();
// 0
+arr.pop();
// NaN
const arr = [];
// []
const a = arr.pop();
// undefined
~~a;
// 0
+a;
// NaN
const addStrings = function(str1, str2) {
let res = '';
let temp = 0;
const arr1 = str1.split('');
const arr2 = str2.split('');
while (arr1.length || arr2.length || temp) {
// string => number ✅
let a = ~~arr1.pop();
let b = ~~arr2.pop();
console.log(`a, b`, a, b);
temp += a + b;
console.log(`temp`, temp);
// 字符串相加,要注意先后顺序
res = (temp % 10) + res;
// 进位
temp = temp > 9 ? 1 : 0;
}
// 正则表达式去除头部的 0
return res === "0" ? res : res.replace(/^0+/, '');
}
/*
addStrings([1,0,0,0,0,1].join(``), [4, 5, 6].join(``));
a, b 1 6
temp 7
a, b 0 5
temp 5
a, b 0 4
temp 4
a, b 0 0
temp 0
a, b 0 0
temp 0
a, b 1 0
temp 1
'100457'
*/
const addStrings = function(str1, str2) {
let res = '';
let temp = 0;
const arr1 = str1.split('');
const arr2 = str2.split('');
while (arr1.length || arr2.length || temp) {
// string => number ❌ NaN bug
let a = +arr1.pop();
let b = +arr2.pop();
console.log(`a, b`, a, b);
temp += a + b;
console.log(`temp`, temp);
// 字符串相加,要注意先后顺序
res = (temp % 10) + res;
// 进位
temp = temp > 9 ? 1 : 0;
}
// 正则表达式去除头部的 0
return res === "0" ? res : res.replace(/^0+/, '');
}
addStrings([1,0,0,0,0,1].join(``), [4, 5, 6].join(``));
/*
a, b 1 6
temp 7
a, b 0 5
temp 5
a, b 0 4
temp 4
a, b 0 NaN
temp NaN
a, b 0 NaN
temp NaN
a, b 1 NaN
temp NaN
'NaNNaNNaN457'
*/
demos
const addStrings = function(str1, str2) {
let res = '';
let temp = 0;
const arr1 = str1.split('');
const arr2 = str2.split('');
while (arr1.length || arr2.length || temp) {
// string => number ✅
// ~~ double bitwise not / 双非位运算
temp += ~~arr1.pop() + ~~arr2.pop();
console.log(`temp`, temp);
// 字符串相加,要注意先后顺序
res = (temp % 10) + res;
// 进位
temp = temp > 9 ? 1 : 0;
}
// 正则表达式去除头部的 0
return res === "0" ? res : res.replace(/^0+/, '');
}
addStrings([1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1].join(``), [4, 5, 6].join(``));
/*
2 x temp 6
temp 4
27 x temp 0
temp 1
'1000000000000000000000000000466'
*/
❌ NaN bug
+0
const addStrings = function(str1, str2) {
let res = '';
let temp = 0;
const arr1 = str1.split('');
const arr2 = str2.split('');
while (arr1.length || arr2.length || temp) {
// string => number ❌ NaN bug
temp += +arr1.pop() + +arr2.pop();
console.log(`temp`, temp);
// 字符串相加,要注意先后顺序
res = (temp % 10) + res;
// 进位
temp = temp > 9 ? 1 : 0;
}
// 正则表达式去除头部的 0
return res === "0" ? res : res.replace(/^0+/, '');
}
addStrings([1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1].join(``), [4, 5, 6].join(``));
/*
temp 7
temp 5
temp 4
28 x temp NaN
'NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN457'
*/
!
js 大数相加,科学计数法 bug
const a = parseInt([1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1].join(``));
const b = parseInt([4, 6, 5].join(``));
const sum = a + b;
// 1e+30 ❌
// wanted ✅
// 1000000000000000000000000000466