fix: off-by-one error in binary_count_trailing_zeros for zero input (#14479)#14480
Open
zendy199x wants to merge 1 commit intoTheAlgorithms:masterfrom
Open
Conversation
Contributor
There was a problem hiding this comment.
Pull request overview
Updates binary_count_trailing_zeros to treat 0 as invalid input (instead of returning 0), aligning behavior with the mathematical undefined/infinite nature of trailing zeros for zero.
Changes:
- Updated doctest to expect a
ValueErrorforbinary_count_trailing_zeros(0). - Removed the
a == 0fallback return path so the function no longer returns0for zero input.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
"The function returns `0` for `a == 0`, but mathematically, trailing zeros in binary representation of 0 are undefined (or conventionally treated as infinite). While `log2(a & -a)` fails for `a=0`, the current fallback to `0` is inconsistent with the documented behavior: `binary_count_trailing_zeros(16)` returns `4`, but `0` has infinitely many trailing zeros — returning `0` is misleading and could cause bugs in algorithms relying on this (e.g., bit manipulation loops expecting correct trailing zero counts)." Signed-off-by: Zendy <50132805+zendy199x@users.noreply.github.com>
37b7435 to
fcf063b
Compare
This file contains hidden or 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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #14479
Describe your change:
Checklist: