Created
August 30, 2020 18:13
-
-
Save muthhukumar/d87ab7f075f011f6a2bef3fc39f48dff to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { logger } = require('./logger/log4js.config'); | |
// main function that calculates no of ones and zeros in a binary value of a number | |
const findNoOfOnesAndZeros = number => { | |
let binaryValue = 0; | |
const count = { | |
numberOfOnes: 0, | |
numberOfZeros: 0, | |
}; | |
if (number <= 0) | |
return { | |
count: { | |
...count, | |
numberOfZeros: 1, | |
}, | |
binaryValue, | |
}; | |
else if (number > 0) { | |
binaryValue = number.toString(2); | |
while (number !== 0) { | |
number % 2 === 0 | |
? count.numberOfZeros++ | |
: number === 1 && count.numberOfOnes++; | |
number >>= 1; | |
} | |
} | |
return { count, binaryValue }; | |
}; | |
// Main function call | |
logger.info(findNoOfOnesAndZeros(-2)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment