查找 L 到 R 中的数字,这与提高到 setbit 计数的数字总和相同
给定一个数字范围[L, R] ,任务是找到给定范围内的所有数字X使得X = 数字之和提升到 X 的 setbit 计数,即,如果在 X 和 X 的二进制表示中有N个 setbits = x 1 x 2 x 3 … 然后 X = (x 1 ) N + (x 2 ) N + (x 3 ) N + 。 . .
例子:
Input: L = 0, R = 10000
Output: 1, 2, 4, 8, 4150, 9474
Explanation: For 2 (binary = 10): setbit count = 1. and 2 = 2^1.
So this is a required number. Same for the other numbers also.
Input: L = 10000, R = 1000000
Output: -1
Explanation: There are no such numbers in the given range.
方法:给定的问题可以通过检查 [L, R] 范围内的所有数字以及它们是否满足条件来解决。这可以在Brian Kernighan 的算法的帮助下完成。
请按照以下步骤解决问题。
- 运行从L到R的循环,并在每次迭代中检查数字是否为索引号。
- 首先从其二进制表示中计算十进制数中的设置位数。
- 然后, Initialize Original = N , Res = 0 , Index = Count of Set bits 。
- 在 N > 0 时运行一个循环
- 从数字中找到最后一位数字说( L ),
- 将L索引添加到Res。
- 从号码中删除最后一位数字。
- 如果Original = Res ,这将是所需数字之一。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
#define ll long long
// Function to return Number of
// set bits in any decimal number
int countSetBits(ll N)
{
int Count = 0;
while (N) {
N = N & (N - 1);
Count++;
}
return Count;
}
// Function to check whether the
// number is index number or not
bool check(int Index, ll N)
{
ll Original = N, Res = 0;
if(N == 0)
return false;
while (N != 0) {
int L = N % 10;
Res += pow(L, Index);
N = N / 10;
}
return Original == Res;
}
// Function to find the numbers
vector findNum(int l, int r)
{
// Vector to store the numbers
vector ans;
for (ll i = l; i <= r; i++) {
int BitCount = countSetBits(i);
if (check(BitCount, i))
ans.push_back(i);
}
return ans;
}
// Driver Code
int main()
{
int L = 0, R = 10000;
// Function call
vector res = findNum(L, R);
if(res.size()==0)
cout << -1 << endl;
for (int x : res)
cout << x << " ";
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG {
// Function to return Number of
// set bits in any decimal number
static int countSetBits(long N)
{
int Count = 0;
while (N != 0) {
N = N & (N - 1);
Count++;
}
return Count;
}
// Function to check whether the
// number is index number or not
static boolean check(int Index, long N)
{
long Original = N, Res = 0;
if(N == 0)
return false;
while (N != 0) {
long L = N % 10;
Res += Math.pow(L, Index);
N = N / 10;
}
return Original == Res;
}
// Function to find the numbers
static Vector findNum(int l, int r)
{
// Vector to store the numbers
Vector ans = new Vector();
for (int i = l; i <= r; i++) {
int BitCount = countSetBits(i);
if (check(BitCount, i))
ans.add(i);
}
return ans;
}
// Driver Code
public static void main (String[] args) {
int L = 0, R = 10000;
// Function call
Vector res = findNum(L, R);
if(res.size()==0)
System.out.println(-1);
res.forEach((x) -> System.out.print(x + " "));
}
}
// This code is contributed by hrithikgarg03188.
Javascript
输出
1 2 4 8 4150 9474
时间复杂度: O(R * d) 其中d是数字中的最大位数
辅助空间: O(1)