Is not arithmetic shift better in countSetBits.js?

Open
#1,152 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
38/100
Issue type
Refactor
Clarity
Mostly clear
Activity status
Stale
Tech stack
javascript
Domain
tooling

Research direction

Start in countSetBits.js at the shift on the line using >>>= 1. Read the surrounding function and any nearby tests or documentation to determine the intended behavior for negative numbers. Done means the shift behavior is explicitly settled and the implementation and relevant tests consistently reflect that decision.

Written by the indexing model from the issue text.

Description

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.

Dominant language
JavaScript
Stars
197k
Forks
31k
PR merge metrics
No merged PRs in 30d

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from trekhleb/javascript-algorithms

All issues in trekhleb/javascript-algorithms

Similar issues

More JavaScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.