📜  以0到N的二进制表示形式翻转/翻转的总位数

📅  最后修改于: 2021-04-24 03:25:48             🧑  作者: Mango

给定一个整数N ,任务是查找被翻转以按顺序获得从0N的所有数字的位数。

例子:

方法:
请按照以下步骤解决问题:

  • 需要解决以下问题:
  • 因此,我们可以得出结论,第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)