给定一个整数N ,任务是查找被翻转以按顺序获得从0到N的所有数字的位数。
例子:
Input: N = 5
Output: 8
Explanation:
Let’s represent numbers from 0 to 5 in binary:
000 -> 001 : 1 bit toggled
001 -> 010 : 2 bits toggled
010 -> 011 : 1 bit toggled
011 -> 100 : 3 bits toggled
100 -> 101 : 1 bit toggled
Hence, 8 bits toggled
Input: N = 1
Output: 1
方法:
请按照以下步骤解决问题:
- 需要解决以下问题:
The rightmost bit toggles every time.
(000) -> (001) -> (010) -> (011)
So, the contribution of this bit to the count will be N.
The next bit toggles after every 2 numbers.
(000) -> (001) -> (010) -> (011) -> (100)
Hence, the contribution of this bit to the count will be N/2.
- 因此,我们可以得出结论,第i个最低有效位将对触发计数贡献N /(2 i ) 。
- 因此,其中i在[0,log 2 N]范围内的N /(2 i )之和给出了所需的答案。
- 因此,初始化变量ans 。将N加到ans并将N更新为N / 2 。重复此过程,直到N变为0,以获得最终结果。
下面是上述方法的实现:
C++
// C++ program to count
// the number of toggles
// required to generate
// all numbers from 0 to N
#include
using namespace std;
typedef long long int ll;
// Function to count and print
// the required number of
// toggles
void solve(ll N)
{
// Store the count
// of toggles
ll ans = 0;
while (N != 0) {
// Add the contribution
// of the current LSB
ans += N;
// Update N
N /= 2;
}
// Print the result
cout << ans << endl;
}
// Driver code
int main()
{
ll N = 5;
solve(N);
return 0;
}
Java
// Java program to count the
// number of toggles required
// to generate all numbers
// from 0 to N
class GFG{
// Function to count and print
// the required number of
// toggles
static void solve(int N)
{
// Store the count
// of toggles
int ans = 0;
while (N != 0)
{
// Add the contribution
// of the current LSB
ans += N;
// Update N
N /= 2;
}
// Print the result
System.out.println(ans);
}
// Driver code
public static void main(String []args)
{
int N = 5;
solve(N);
}
}
// This code is contributed by Ritik Bansal
Python3
# Python3 program to count
# the number of toggles
# required to generate
# all numbers from 0 to N
# Function to count and pr
# the required number of
# toggles
def solve(N):
# Store the count
# of toggles
ans = 0
while (N != 0):
# Add the contribution
# of the current LSB
ans += N
# Update N
N //= 2
# Print the result
print(ans)
# Driver code
N = 5
solve(N)
# This code is contributed by code_hunt
C#
// C# program to count the
// number of toggles required
// to generate all numbers
// from 0 to N
using System;
class GFG{
// Function to count and print
// the required number of
// toggles
static void solve(int N)
{
// Store the count
// of toggles
int ans = 0;
while (N != 0)
{
// Add the contribution
// of the current LSB
ans += N;
// Update N
N /= 2;
}
// Print the result
Console.Write(ans);
}
// Driver code
public static void Main(string []args)
{
int N = 5;
solve(N);
}
}
// This code is contributed by rock_cool
Javascript
输出:
8
时间复杂度: O(log N)
辅助空间: O(1)