Skip to content

Is not arithmetic shift better in countSetBits.js? #1152

Open
@oThinas

Description

@oThinas

The file countSetBits.js has the function:

/**
 * @param {number} originalNumber
 * @return {number}
 */
export default function countSetBits(originalNumber) {
  let setBitsCount = 0;
  let number = originalNumber;

  while (number) {
    // Add last bit of the number to the sum of set bits.
    setBitsCount += number & 1;

    // Shift number right by one bit to investigate other bits.
    number >>>= 1;
  }

  return setBitsCount;
}

I wonder if it wouldn't be better to use an arithmetic shift on line number >>>= 1 instead of a logical shift, thus preserving the sign of the number.

Activity

linked a pull request that will close this issue on Jul 20, 2024
added a commit that references this issue on Aug 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      Participants

      @oThinas

      Issue actions

        Is not arithmetic shift better in countSetBits.js? · Issue #1152 · trekhleb/javascript-algorithms