给定数字N ,任务是找到从0到N的连续数字的汉明差之和。
Hamming Distance between two integers is the number of bits which are different at the same position in both numbers.
例子:
Input: 5
Output: 8
Explanation:
Difference between (0, 1) = 1, (1, 2) = 2,
(2, 3) = 1, (3, 4) = 3, (4, 5) = 1.
So the total sum is 1 + 2 + 1 + 3 + 1 = 8
Input: 9
Output: 16
朴素和对数方法:朴素的方法是指从0到N的数字的位差之和,而对数方法是基于检查N是否为2的幂来计算和。
方法:在本文中,讨论了一种基于观察从LSB到MSB的所有位中发生的更改数量的方法。
请按照以下步骤解决问题:
- 可以看出,最低有效位将改变N次。第二最低有效位将改变下限(N / 2)次(即,如果N为奇数,则为(N – 1)/ 2),如果N为偶数,则为N / 2。因此,第i个比特将改变floor(N / 2 i )次。
- 因此,为了解决这个问题,我们可以简单地存储和
N + floor(N/2) + … floor(N/2i)
- 直到该项不为零。
下面是上述方法的实现:
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)