Skip to content

[FEATURE REQUEST] Find Nth bit of a number #5732

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Tuhinm2002 opened this issue Oct 12, 2024 · 1 comment
Closed

[FEATURE REQUEST] Find Nth bit of a number #5732

Tuhinm2002 opened this issue Oct 12, 2024 · 1 comment

Comments

@Tuhinm2002
Copy link
Contributor

What would you like to Propose?

The algo finds the nth bit of a given number using bit manipulation techniques

  • Space complexity O(1)

  • Time complexity O(1)

  • Test

package com.thealgorithms.bitmanipulation;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

public final class FindNthBitTest {

    /**
     * A parameterized test that checks the value of the Nth bit for different inputs.
     *
     * @param num     the number whose Nth bit is being tested
     * @param n       the bit position
     * @param expected the expected value of the Nth bit (0 or 1)
     */
    @ParameterizedTest
    @MethodSource("provideTestCases")
    void findNthBitParameterizedTest(int num, int n, int expected) {
        assertEquals(expected, FindNthBit.findNthBit(num, n));
    }

    /**
     * Provides the test cases as a stream of arguments for the parameterized test.
     *
     * @return a stream of test cases where each case consists of a number, the bit position,
     * and the expected result.
     */
    private static Stream<Arguments> provideTestCases() {
        return Stream.of(Arguments.of(13, 2, 0), // binary: 1101, 2nd bit is 0
            Arguments.of(13, 3, 1), // binary: 1101, 3rd bit is 1
            Arguments.of(4, 2, 0), // binary: 100, 2nd bit is 0
            Arguments.of(4, 3, 1), // binary: 100, 3rd bit is 1
            Arguments.of(1, 1, 1) // binary: 1, 1st bit is 1
        );
    }
}

Issue details

An important missing algorithm from bit manipulation pacakge

Additional Information

No response

@Tuhinm2002
Copy link
Contributor Author

@siriak check this missing algo here #5731

@alxkm alxkm closed this as completed Oct 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants