📜  从0到N的连续数字的汉明差总和|套装2

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

给定数字N ,任务是找到从0到N的连续数字的汉明差之和。

例子:

朴素和对数方法:朴素的方法是指从0到N的数字的位差之和,而对数方法是基于检查N是否为2的幂来计算和。

方法:在本文中,讨论了一种基于观察从LSB到MSB的所有位中发生的更改数量的方法。
请按照以下步骤解决问题:

  • 可以看出,最低有效位将改变N次。第二最低有效位将改变下限(N / 2)次(即,如果N为奇数,则为(N – 1)/ 2),如果N为偶数,则为N / 2。因此,第i比特将改变floor(N / 2 i )次。
  • 直到该项不为零。

下面是上述方法的实现:

C++
// C++ Program to implement 
// the above approach 
  
#include  
using namespace std; 
  
// Function to calculate and 
// return the hamming distance 
// between all consecutive 
// numbers from 0 to N 
int TotalHammingDistance(int n) 
{ 
    int i = 1, sum = 0; 
    while (n / i > 0) { 
        sum = sum + n / i; 
        i = i * 2; 
    } 
    return sum; 
} 
  
// Driver Code 
int main() 
{ 
    int N = 9; 
    cout << TotalHammingDistance(N); 
    return 0; 
}


Java
// Java program to implement the
// above approach
import java.util.*;
  
class GFG{
  
// Function to calculate and
// return the hamming distance
// between all consecutive 
// numbers from 0 to N
static int TotalHammingDistance(int n)
{
    int i = 1, sum = 0;
    while (n / i > 0) 
    {
        sum = sum + n / i;
        i = i * 2;
    }
    return sum;
}
  
// Driver code
public static void main(String[] args)
{
    int N = 9;
      
    System.out.println(TotalHammingDistance(N));
}
}
  
// This code is contributed by offbeat


Python3
# Python3 program to implement 
# the above approach 
  
# Function to calculate and 
# return the hamming distance 
# between all consecutive 
# numbers from 0 to N 
def TotalHammingDistance(n): 
      
    i = 1
    sum = 0
      
    while (n // i > 0): 
        sum = sum + n // i 
        i = i * 2
          
    return sum
  
# Driver Code 
if __name__ == '__main__': 
      
    N = 9
      
    print(TotalHammingDistance(N)) 
  
# This code is contributed by mohit kumar 29


C#
// C# Program to implement 
// the above approach 
using System; 
class GFG{ 
  
// Function to calculate and 
// return the hamming distance 
// between all consecutive 
// numbers from 0 to N 
static int TotalHammingDistance(int n) 
{ 
    int i = 1, sum = 0; 
    while (n / i > 0) 
    { 
        sum = sum + n / i; 
        i = i * 2; 
    } 
    return sum; 
} 
  
// Driver Code 
public static void Main() 
{ 
    int N = 9; 
    Console.Write(TotalHammingDistance(N)); 
} 
} 
  
// This code is contributed by Code_Mech


输出:
16

时间复杂度: O(logN)
辅助空间: O(1)