给定两个整数N和K,任务是找到第K个位已设置的N个数的计数。
例子:
Input: N = 14, K = 2
Output: 7
Explanation:
The numbers less than equal to 14, having 2nd bit set are 4, 5, 6, 7, 12, 13, and 14.
Input: N = 6, K = 1
Output: 3
Explanation:
The numbers less than equal to 6 having 1st bit set are 1, 3, 5.
天真的方法:最简单的方法是从1遍历到N ,并检查每个数字的第K位是否已置位。
时间复杂度: 上)
辅助空间: O(1)
高效方法:可以优化上述方法 通过将任务分为两部分:
- 首先,将N右移K + 1次,然后将结果左移K次,得出满足给定条件的数 直到小于N的最接近2的幂。
- 现在,检查第K个位被设置在N或没有。
- 如果将第K位设置为N,则将答案的数字从小于N的最接近2的幂开始增加。
下面是上述方法的实现:
C++
// C++ program for above approach
#include
using namespace std;
// Function to return the count
// of number of 1's at ith bit
// in a range [1, n - 1]
long long getcount(long long n, int k)
{
// Store count till nearest
// power of 2 less than N
long long res = (n >> (k + 1)) << k;
// If K-th bit is set in N
if ((n >> k) & 1)
// Add to result the nearest
// power of 2 less than N
res += n & ((1ll << k) - 1);
// Return result
return res;
}
// Driver Code
int main()
{
long long int N = 14;
int K = 2;
// Function Call
cout << getcount(N + 1, K) << endl;
return 0;
}
Java
// Java program for above approach
class GFG
{
// Function to return the count
// of number of 1's at ith bit
// in a range [1, n - 1]
static long getcount(long n, int k)
{
// Store count till nearest
// power of 2 less than N
long res = (n >> (k + 1)) << k;
// If K-th bit is set in N
if (((n >> k) & 1) != 0)
// Add to result the nearest
// power of 2 less than N
res += n & ((1 << k) - 1);
// Return result
return res;
}
// Driver code
public static void main(String[] args)
{
long N = 14;
int K = 2;
// Function Call
System.out.println(getcount(N + 1, K));
}
}
// This code is contributed by divyesh072019
Python3
# Python3 program for above approach
# Function to return the count
# of number of 1's at ith bit
# in a range [1, n - 1]
def getcount(n, k):
# Store count till nearest
# power of 2 less than N
res = (n >> (k + 1)) << k
# If K-th bit is set in N
if ((n >> k) & 1):
# Add to result the nearest
# power of 2 less than N
res += n & ((1 << k) - 1)
# Return result
return res
# Driver Code
if __name__ == '__main__':
N = 14
K = 2
# Function Call
print (getcount(N + 1, K))
# This code is contributed by mohit kumar 29
C#
// C# program for above approach
using System;
class GFG{
// Function to return the count
// of number of 1's at ith bit
// in a range [1, n - 1]
static long getcount(long n, int k)
{
// Store count till nearest
// power of 2 less than N
long res = (n >> (k + 1)) << k;
// If K-th bit is set in N
if (((n >> k) & 1) != 0)
// Add to result the nearest
// power of 2 less than N
res += n & ((1 << k) - 1);
// Return result
return res;
}
// Driver Code
static void Main()
{
long N = 14;
int K = 2;
// Function Call
Console.WriteLine(getcount(N + 1, K));
}
}
// This code is contributed by divyeshrabadiya07
Javascript
输出:
7
时间复杂度: O(1)
辅助空间: O(1)