最小化 2 的幂的减法以将 N 转换为 0
给定一个正整数N ,任务是找到将N转换为 0 所需的 2 次幂减法的最小次数。
例子:
Input: 10
Output: 2
Explanation: When we subtract 8 from 10 ( 10 – (2^3) = 2) then 2 will remain.
After that subtract 2 from 2^0 i.e., 2 – 2^0 = 0.
Hence we are doing two operation to make the N = 0.
Input: 5
Output: 2
方法:问题的方法基于以下思想:
As we need to minimize the number of subtractions then subtract as big a a power of 2 as possible. This will be same as the number of set bits in the binary representation of N.
请按照下图进行更好的理解。
插图:
Take N = 10
1st step: The maximum value that can be subtracted is 8
So N = 10 – 8 = 2.
2nd step: The maximum value that can be subtracted is 2
So N = 2 – 2 = 0.
Now see the binary representation of 10 = “1010”.
It has 2 set bits. So minimum steps required = 2
请按照以下步骤实施该方法:
- 从i = 1 迭代到 63 :
- 检查是否设置了 N 的二进制表示的那个位。
- 如果设置,则增加设置位的计数。
- 返回设置位的最终计数。
以下是上述方法的实现。
C++
// C++ code to implement the approach
#include
using namespace std;
// Function to find the number of
// operation to make the N zero
int find_no_of_set_bits(long long n)
{
// Take variable to count the number
// of operation
int set_bit_count = 0;
for (int i = 0; i < 63; i++) {
if (n & (1LL << i)) {
set_bit_count++;
}
}
return set_bit_count;
}
// Driver code
int main()
{
long long N = 10;
// Function call
cout << find_no_of_set_bits(N) << endl;
return 0;
}
2
时间复杂度: O(1)
辅助空间: O(1)