📜  从0到N的数字的位差总和|套装2

📅  最后修改于: 2021-05-25 01:34:08             🧑  作者: Mango

给定数字N ,任务是为从0到N的每个连续数字计算二进制表示形式中相应不同位的总数。

例子:

对于朴素和有效的方法,请参阅本文的上一篇文章。

更有效的方法:为了优化上述方法,我们可以使用递归。要解决此问题,需要进行以下观察

Number:     0 1 2 3 4  5  6  7
Difference: 1 2 1 3 1  2  1  4
Sum:        1 3 4 7 8 10 11 15

我们可以观察到,对于N = [1,2,3,4,…] ,连续元素中不同位的总和形成序列[1、3、4、7、8,……] 。因此,本系列的N术语将是我们所需的答案,可以将其计算为:

以下是上述递归方法的实现:

C++
// C++ program to find the sum
// of bit differences between
// consecutive numbers
// from 0 to N using recursion
  
#include 
using namespace std;
  
// Recursive function to find sum
// of different bits between
// consecutive numbers from 0 to N
int totalCountDifference(int n)
{
  
    // Base case
    if (n == 1)
        return 1;
  
    // Calculate the Nth term
    return n
           + totalCountDifference(n / 2);
}
  
// Driver Code
int main()
{
    // Given Number
    int N = 5;
  
    // Function Call
    cout << totalCountDifference(N);
    return 0;
}


Java
// Java program to find the sum
// of bit differences between
// consecutive numbers from 
// 0 to N using recursion
class GFG{
  
// Recursive function to find sum
// of different bits between
// consecutive numbers from 0 to N
static int totalCountDifference(int n)
{
  
    // Base case
    if (n == 1)
        return 1;
  
    // Calculate the Nth term
    return n + totalCountDifference(n / 2);
}
  
// Driver Code
public static void main(String[] args)
{
      
    // Given number
    int N = 5;
  
    // Function call
    System.out.println(totalCountDifference(N));
}
}
  
// This code is contributed by himanshu77


Python3
# Python3 program to find the sum
# of bit differences between
# consecutive numbers from
# 0 to N using recursion
  
# Recursive function to find sum
# of different bits between
# consecutive numbers from 0 to N
def totalCountDifference (n):
  
    # Base case
    if (n == 1):
        return 1
  
    # Calculate the Nth term
    return n + totalCountDifference(n // 2)
  
# Driver code
  
# Given number
N = 5
  
# Function call
print(totalCountDifference(N))
  
# This code is contributed by himanshu77


C#
// C# program to find the sum
// of bit differences between
// consecutive numbers from
// 0 to N using recursion
using System;
  
class GFG{
  
// Recursive function to find sum
// of different bits between
// consecutive numbers from 0 to N
static int totalCountDifference(int n)
{
  
    // Base case
    if (n == 1)
        return 1;
  
    // Calculate the Nth term
    return n + totalCountDifference(n / 2);
}
  
// Driver Code
public static void Main()
{
      
    // Given number
    int N = 5;
  
    // Function call
    Console.WriteLine(totalCountDifference(N)); 
}
}
  
// This code is contributed by himanshu77


输出:
8


时间复杂度: O(log 2 N)
辅助空间: O(1)

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。