Algorithm questions daily practice---Day 63: Excellent split

Offer arrives, dig friends to pick up! I am participating in the 2022 Spring Recruitment Check-In Event, click to view the event details .

1. Problem description

In general, a positive integer can be split into the sum of several positive integers.

If a positive integer can be split into several different 正整数power-of-2 forms, then call it 优秀的拆分.

E.g, 10 = 8 + 2 = 2 3 + 2 1 10=8+2=2^3+2^1 is an excellent split. but, 7 = 4 + 2 + 1 = 2 2 + 2 1 + 2 0 7=4+2+1=2^2+2^1+2^0  is not a good split because 1 is not a positive integer power of 2.

Now, given a positive integer n, you need to determine whether there is a good split among all the splits of this number. If so, please give a specific split plan.

Topic link: Excellent split .

Second, the subject requirements

Example 1

输入: 10
输出: 8 2
复制代码

Example 2

输入: 7
输出:-1
复制代码

visit

1.位运算
2.建议用时15~30min
复制代码

3. Problem Analysis

This question is the 18th question of bit operation. If you don't know the relevant knowledge points of bit operation, you can read this article. The explanation is more detailed:

Algorithm questions are practiced daily --- Day 45: Bit operations .

To put it simply, this question needs to determine whether a number can be divided into different powers of 2 and added together. 2 0 2^0 does not count.

If the input is an odd number, output -1, which does not exist.

Int 32 bits can store the amount of data for this question, for example:

10->2进制:  1 0 1 0
对应10进制:8 0 2 0
复制代码

Then we only need to right- shift and calculate the binary of the number from the binary head (ie, 31 bits) , if it is 1, output the corresponding decimal result, if it is 0, skip it.

Fourth, the encoding implementation

#include<iostream>
#include<math.h>
using namespace std;
int main()
{	
	long long  i,j,n,k;//初始化数据
	cin>>n;//输入n
	if(n%2!=0)//奇数直接输出-1
	{
		cout<<-1;
		return 0;
	}
	else
	{
		for(i=31;i>=0;i--)//从2进制31位开始右移计算
		{
			if(n&(1<<i))//如果的当前位是1
			{
				k=pow(2,i);
				cout<<k<<" ";//输出结果
			}
		}
	}
	return 0;
}
复制代码

5. Test results

1.png

おすすめ

転載: juejin.im/post/7078850115087106084