Count Bits from unsigned integer - javascript

I am attempting to write a function that takes an (unsigned) integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case.
Here is my answer:
var newArr;
var count = 0;
function countBits(num){
newArr = num.toString(2).split('').map(function(el){
if(el == '1')
count++
});;
return count;
}
In my program when I call countBits(7) it returns //3 but when I submit my response it says it is returning //4. Can someone see what I am missing in my response based on question?

Your problem is that you are declaring the variables outside of the function, so when the function is called multiple times they'll keep their values and just increase the count.
Btw, you also shouldn't use map if you don't want to create another array - so better do
function countBits(num){
var newArr = num.toString(2).split('').map(Number);
var count = 0;
for (var i=0; i<newArr.length; i++)
count += newArr[i];
}
return count;
}
or
function countBits(num){
return num.toString(2).split('').reduce(function(count, el) {
return count + (el == "1");
}, 0);
}

function countBits(num){
/* Convert num Base10 to num Base2
then find Ones and save them in an array
length of the array is equal their sum */
return num.toString(2).match(/1/g).length
}

function countBits(num){
// convert num Base10 to Base2
let base2 = num.toString(2)
// declare variable for sum of bits
let sum = 0
// for loop to check bits (bit = 1) and ignore Zeros in the String base2
for(let i = 0; i < base2.length; i++){
if(base2[i] == 1){
// use Number() to convert string to number
count += Number(base2[i])
}
}
return sum ;
}

Related

Why is the Number() function not working when I use it this way?

function sumDigits(num) {
// your code here
let nums = num.toString();
let sum = 0;
for(let i = 0;i<nums.length;i++){
Number(nums[i]);
console.log(typeof nums[i]);
sum += nums[i];
}
return sum;
}
var output = sumDigits(1148);
console.log(output); // --> 14
Can someone explain why Number(nums[i]) does not change the type of the variable. Or any other way to solve this problem? The function is supposed to take in an integer value and add all the digits and return an integer.
When I tried to run the code i couldn't get the string to convert back into a number and would just add the value of sums to the front of the string.
You are not saving the value returned by Number(nums[i]). But since here you are not using it more than once, you can just add it to the sum without assigning it to a variable.
function sumDigits(num) {
// your code here
let nums = num.toString();
let sum = 0;
for (let i = 0; i < nums.length; i++) {
sum += Number(nums[i]);
}
return sum;
}
var output = sumDigits(1148);
console.log(output); // --> 14
Number does not change the value it's used on. (It couldn't when used on a string, anyway, since strings in JavaScript are immutable.) It just returns a number. So you have to use that return value.
Try this instead:
for(let i = 0; i < nums.length; i++){
sum += Number(nums[i]);
}
To fix your code, change sum += nums[i]; to sum += Number(nums[i]);. Reason: When you add a string to a number, the number is first converted to a string, and a string concatenation is performed.
Here is a functional programming approach to your question:
function sumDigits(num) {
return num.toString() // convert number to string
.split('') // split into array of chars
.reduce((acc, val) => { // reduce array to sum of items
return acc + Number(val)
}, 0);
}
var output = sumDigits(1148);
console.log(output); // --> 14
Functional programming makes code more extensible, modular, reusable, performing, and testable.
Into to functional programming in JavaScript:
https://opensource.com/article/17/6/functional-javascript
.reduce() docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
Here is the same with a map reduce approach:
function sumDigits(num) {
return num.toString() // convert number to string
.split('') // split into array of chars
.map(char => Number(char)) // change each char in array to number
.reduce((acc, val) => { // reduce array to sum of items
return acc + val
}, 0);
}
var output = sumDigits(1148);
console.log(output); // --> 14
Intro to map reduce: https://medium.com/poka-techblog/simplify-your-javascript-use-map-reduce-and-filter-bd02c593cc2d

Number of 1 Bits with Javascript

Question: Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
Example 1:
Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
My Code
var hammingWeight = function(n) {
for (i=0; i<32; i++) {
var mask = 1;
var count = 0;
if ((mask & n) != 0 ) {
mask <<= 1;
count++;
}
return count;
}
};
Test Case:
00000000000000000000000000001011
00000000000000000000000010000000
11111111111111111111111111111101
Expected Output:
3
1
31
Output:
1
0
1
What did I do wrong with my code?
You have a few issues here:
You are redefining count and mask inside of your for loop.
You are returning after the first iteration of the loop, instead of waiting for the whole thing to count up.
You only shift mask if a bit is 1.
Here is a corrected function:
var hammingWeight = function(n) {
var count = 0;
var mask = 1;
for (i=0; i<32; i++) {
if ((mask & n) != 0 ) {
count++;
}
mask <<= 1;
}
return count;
};
A shorter way to write this could be:
const hammingWeight = value => [...value].filter(f => f == 1).length;
Explanation:
[...value] this will create an array of 0's and 1's based on your string
.filter(f => f == 1) will filter the array, keeping only the 1 values
.length gives you the length of the filtered array

how do I use values from an array inside a function in another function?

I created a function in Javascript that convert decimal numbers to binary, and I used an array to store the binary numbers, and made the function returns the array, what I want is, how do I get the values of that array and use it outside the function or in another function?
thats the function I was talking about, and that array I want is called numArray.
function decimalToBinary(Num) {
let bits = '';
let rem = Num;
for(let i = 7; i >= 0; i--) {
let divisor = Math.pow(2, i);
let bitValue = Math.floor(rem / divisor);
bits = bits + bitValue;
rem = rem % divisor;
}
let numArray = [];
for(let i = 0; i < bits.length; i++){
let bit = bits.charAt(i);
let binaryNums = parseInt(bit);
numArray.push(binaryNums);
}
return numArray;
}
/*
what I want to do is to use a specific value from inside that array
and use inside a second function, and then use if-statement to get the
result I want
*/
function second() {
//if-statement
if(numArray[2] === 1){
//do something
}else{
//do something else
}
}
var binary = [] ;
function decimalToBinary(Num) {
// do some logic push the output in binary
return binary;
}
function second(argument){
//Here you can access the binary
}
P.S:- This is anti pattern if you update your question i can tell some more way to do it.

Sum of range in array

I am having a huge issue with a coding problem I need to make. I am being asked to run a sum of numbers inside of an array and I can't get the code to run properly.
This is my code and below are the instructions of what I am being asked to run:
function sumOfRange(numbers){
var numbers = [1,-1,1,-1,1];
var sum = 0;
for (var i = 0; i < numbers.length; i++){
sum += numbers[i];
}
return sum;
}
// Your Challenge:
// - Create a function named sumOfRange.
// - It accepts one parameter, called numbers, that
// represents an array of numbers.
//
// - In your function, sum the numbers inside the array.
// (Reminder: you'll need a variable to store the result.)
// - Return the result.
// Hint: You do not need to create a new array - you will be
// looping through the parameter, which is already coming in as
// an array.
// Someone else will be calling your function like this:
// sumOfRange([1,2,3,4,5])
// sumOfRange([-4,-5,-10,0])
I keep getting
errors saying
You returned '1'. That isn't quite right. The sum of [1,2,3,4,5] is 15.
Any help with this would greatly appreciate it.
Remove the first line of your function sumOfRange() var numbers = [1,-1,1,-1,1] because you are re-initializing the value of numbers, you need to use to array that is passed to the function when it is called.
function sumOfRange(numbers) {
var sum = 0;
for (var i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
return sum;
}
console.log(sumOfRange([1,-1,1,-1,1]));
console.log(sumOfRange([1,2,3,4,5]));
console.log(sumOfRange([-4,-5,-10,0]));
var a = [1,2,3,4,5];
function sum (arr) {
return arr.reduce(function(prev, curr) {
return prev + curr;
}, 0);
}
//sum(a) -> returns 15

Sorting odd and even numbers with the remainder operator Javascript

If a number, when divided by two, has a remainder that is not equal to 0, this number must be odd. I'm trying to use that logic in my if statement to keep only odd values, and get rid of even ones. I'm not sure how I'm doing this wrong, but myArray is returning even values as well as odd. Any ideas?
function sumFibs(num) {
var myArray = [1,1];
// Create fibonacci sequence
// Stop creating fibonacci numbers at num
// Push odd numbers to oddNums array
for (var i = 0; i < myArray.length; i++) {
if (myArray[i+1] + myArray[i] <= num && myArray[i+1] + myArray[i] % 2 !== 0) {
myArray.push(myArray[i+1] + myArray[i]);
}
} // End loop.
console.log(myArray);
// Summation of oddNums array.
return myArray.reduce(function(a,b) {
return a + b;
});
} // End function.
sumFibs(1000);
You are trying to filter odd values while generating your fib sequence, which probably not the best approach. If you wrap the modulo expression in parentheses,
(myArray[i+1] + myArray[i]) % 2
Your array will not contain the values necessary to continue generating the sequence. Ideally you should generate the full fib series and then filter:
var myArray = [1,1];
for (var i = 0; i <= num; i++) {
myArray.push(myArray[i+1] + myArray[i]);
} // End loop.
myArray = myArray.filter(function(a){ return a%2 !== 0 })
or save some reference to the even values so that they can be used to calculate the desired subset of the series.

Categories

Resources