Reworked solution to use bitwise operations.