I can't split a bunch of numbers when the function is a number - why? How do you do this?
I'm attempting https://leetcode.com/problems/number-of-1-bits/
Ways to split a Number into an Array
Accepted answer:
Well, let's look how it works
num + ''.split('') works like
num
is a number''.split('')
is empty array and it's not a number- so, we have sum of a number and not a number, we will cast num and [] to string
num
to string is '969',[]
to string is '' (empty)- '969' + '' = '969'
num.toString() + ''.split('') works like
num.toString()
is a string- ''.split('') is empty array
- so, we have sum of a string and not a string, we will cast
[]
to string[]
to string is '' (empty)- '969' + '' = '969'
String(num).split('') works like
- lets cast
num
to string- and split it by ''
- result of split is array ['9', '6', '9']
Of course when I try it....it doesn't work:
var hammingWeight = function(n) {
let oneBits = String(n).split('');
console.log(oneBits)
};
hammingWeight(0000011110)
What's going on here? Why does it not work?
function hammingWeight(n) {
let oneBits = String(n).split('');
console.log(oneBits)
};
hammingWeight(0000011110)
Why doesn't this work?
function hammingWeight(n) {
let oneBits = n.toString().split('');
console.log(oneBits)
};
hammingWeight(0000011110)
I am beyond confused - where are those numbers coming from?
Binary to String in JavaScript
function hammingWeight(n) {
const oneBits = String.fromCharCode(
...n.split(''))
)
console.log(oneBits)
};
hammingWeight(0000011110)
Doesn't work either!