Skip to content

M1545. 找出第 N 个二进制字符串中的第 K 位

https://leetcode.cn/problems/find-kth-bit-in-nth-binary-string/

cpp
#include <iostream>
#include <vector>
using namespace std;

class Solution
{
public:
    char findKthBit(int n, int k)
    {
        if (n == 1)
            return '0';
        if (k == (1 << (n - 1)))
            return '1';
        if (k < (1 << (n - 1)))
            return findKthBit(n - 1, k);
        return findKthBit(n - 1, (1 << n) - k) ^ 1;
    }
};

int main()
{
    cin.tie(nullptr)->sync_with_stdio(false);

    Solution sol;
    int n = 4, k = 11;
    cout << sol.findKthBit(n, k) << '\n';
    return 0;
}

被0神的方法震撼到了。。。数学,很神奇吧

cpp
class Solution
{
public:
    char findKthBit(int n, int k)
    {
        if (k % 2)
            return '0' + k / 2 % 2;
        k /= k & -k;
        return '1' - k / 2 % 2;
    }
};