PracticeBit Manipulation

Refresh a User's Group Badge

Easy/MediumBit Manipulationtraversalstate trackinginvariants Time not estimated Not started

Context

A social app stores a user's group memberships in one integer badge. Each set binary position represents membership in a particular group. To refresh a badge, toggle the memberships at the lowest and highest occupied positions, leaving all positions between them unchanged.

Problem

Given a nonnegative integer representing one user's group-membership badge, toggle exactly two positions: the lowest set-bit position and the highest set-bit position. Use exclusive combination so every other position remains unchanged. If the badge is zero, no group position exists, so return zero. If only one position is set, it is both endpoints; toggle it once, producing a badge with that position cleared.

Examples

Example 1
Input: badge = 0
Output: 0
Explanation: For badge 0, the executed function returns 0.
Example 2
Input: badge = 8
Output: 0
Explanation: For badge 8, the trace records lowest_mask 8, highest_mask 8, endpoint_mask 8, and output_value 0; the executed function returns 0.
Example 3
Input: badge = 42
Output: 8
Explanation: For badge 42, the trace records lowest_mask 2, highest_mask 32, endpoint_mask 34, and output_value 8; the executed function returns 8.

Constraints

  • 0 <= badge <= 1000000000000000000
  • Types: badge is int; result is int

Function signature

def refresh_group_badge(badge: int) -> int
badge int
A nonnegative integer whose set positions represent the user's group memberships.
returns int
The badge after toggling its lowest and highest set positions once, or zero when the input has no set positions.

Adapted from MBPP problem task_545 (CC BY 4.0). Rewritten, extended and verified by Iksha.

Notes

  • Only nonnegative badges are accepted; the binary representation has no signed extension positions.
  • The endpoint positions are counted from the least-significant position as position zero.
Approved · cc028r1-abs_409_v114 execution-verified tests
Code
Saved
Checking environment…Python SandboxLn 1, Col 1