Advertisement
satishfrontenddev5

Untitled

Jan 6th, 2024
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight).
  3.  
  4. Input format
  5. Single line containing one 32-bit unsigned integer N.
  6.  
  7. Output format
  8. Single line containing number of 1 bits in N.
  9.  
  10. Sample Input 1
  11. 5
  12.  
  13. Sample Output 1
  14. 2
  15.  
  16. Explanation 1
  17. Binary representation of 5 is:
  18.  
  19. 101
  20.  
  21. Hence total number of 1 bits = 2
  22.  
  23. Constraints
  24. 0<=N<=2^32-1
  25. */
  26.  
  27. /**
  28.  * @param {number} n - a positive integer
  29.  * @return {number}
  30.  */
  31. function numberOfOneBits(n) {
  32.     // Implement it here
  33.     let count=0;
  34.     while(n){
  35.         if(n&1)
  36.          count++
  37.         n=n>>>1;
  38.     }
  39.     return count;
  40. }
  41.  
  42. function main() {
  43.     let n = parseInt(readLine(), 10);
  44.     let answer = numberOfOneBits(n);
  45.     print(answer);
  46. }
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement