優秀的拆分(power)


方法一:模擬

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int main()
 4 {
 5     int n;
 6     cin>>n;
 7     if(n%2==1)
 8         cout<<-1;
 9     else{
10         while(n>0){
11             int p=1;
12             while(n>=p)
13                 p*=2;
14             cout<<p/2<<" ";
15             n-=p/2;
16         }
17     }
18     return 0;
19  } 

方法二:位運算(按位&)

舉例說明1:14  的可以最優拆分為 8 4 2

14的二進制1110

8  的二進制1000  與14按位&結果為1000  (8 非0)

4  的二進制0100  與14按位&結果為0100  (4 非0)

2  的二進制0010  與14按位&結果為0010  (2 非0)

舉例說明2:10  的可以最優拆分為 8 2

10的二進制1010

8  的二進制1000  與10按位&結果為1000   (8 非0)

4  的二進制0100  與10按位&結果為0000   (0 )

2  的二進制0010  與10按位&結果為0010   (2 非0)

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int n;
 4 int main()
 5 {
 6     cin>>n;
 7     if(n&1)
 8         cout<<-1;
 9     else{
10         for(int i=31; i>=1; i--){//n值范圍[1,10^7]所以i枚舉范圍[31,1]
11             int t=(1<<i);// 或者 t=pow(2, i);
12             if(t&n)
13             cout<<t<<" ";
14         }
15     }
16     return 0;
17 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM