Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Add Kernighan's Algorithm for Counting Set Bits #1107

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
smitgabani wants to merge 10 commits into TheAlgorithms:master
base: master
Choose a base branch
Loading
from smitgabani:master
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
fixes #1106
  • Loading branch information
smitgabani committed Sep 23, 2022
commit b74962555af1df5457306c385bf0eed1a259d6db
24 changes: 24 additions & 0 deletions Bit-Manipulation/CountSetBits.js
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// author: Smit Gabani
// https://github.com/smitgabani

/**
* explanation link: https://iq.opengenus.org/brian-kernighan-algorithm/
* The below algorithm is called as Brian Kernighan's algorithm
* @param: num takes number whose number of set bit is to be found
* @return: the count of set bits in the binary equivalent
* */
function CountSetBits(num) {
'use strict'
let cnt = 0;
while(num > 0) {
cnt++;
// num = num & (num - 1);
num&=(num-1);
}
return cnt;
}

// console.log(CountSetBits(10))
// expected output: 2

export { CountSetBits }

AltStyle によって変換されたページ (->オリジナル) /