[華為機試練習題]14.整數分隔,華為練習題

來源:互聯網
上載者:User

[華為機試練習題]14.整數分隔,華為練習題

題目

描述:     一個整數總可以拆分為2的冪的和,例如:7=1+2+47=1+2+2+27=1+1+1+47=1+1+1+2+27=1+1+1+1+1+27=1+1+1+1+1+1+1總共有六種不同的拆分方式。再比如:4可以拆分成:4 = 4,4 = 1 + 1 + 1 + 1,4 = 2 + 2,4=1+1+2。用f(n)表示n的不同拆分的種數,例如f(7)=6.要求編寫程式,讀入n(不超過1000000),輸出f(n)%1000000000。題目類別:    null 難度:  初級 已耗用時間限制: 10Sec記憶體限制:   128MByte階段:  入職前練習 輸入:  每組輸入包括一個整數:N(1<=N<=1000000)。輸出:  對於每組資料,輸出f(n)%1000000000。輸出有多行,每行一個結果。輸入資料如果超出範圍,輸出-1。範例輸入:   7範例輸出:   6

思路

當n=2k+1為奇數時,f(2k+1)=f(2k)。其實2k+1的拆分第一項肯定為1,若去掉這個1,就和2k的拆分一樣了。當n=2k為偶數時,我們考慮有1和沒有1的拆分。若有1,則前2項均為1,就和2k-2的拆分一樣了。若沒有1,則將每項除以2,就和k的拆分一樣了。故有f(2k)=f(2k-2)+f(k);

代碼一

/*---------------------------------------*   日期:2015-06-30*   作者:SJF0115*   題目:整數分隔*   來源:華為上機-----------------------------------------*/#include <iostream>#include <string>#include <algorithm>#include <vector>using namespace std;#define Max 1000000int Count[Max+1];int Split(int n){    Count[1] = 1;    Count[2] = 2;    for(int i = 3;i <= n;++i){        // 奇數        if(i % 2){            Count[i] = Count[i-1];        }//if        else{            Count[i] = (Count[i-2] + Count[i/2]) % 1000000000;        }//else    }//for    return Count[n];}int main(){    int n;    //freopen("C:\\Users\\Administrator\\Desktop\\c++.txt","r",stdin);    while(cin>>n){        if(n > Max || n < 0){            return -1;        }//if        cout<<Split(n)<<endl;    }//while    return 0;}

代碼二

逾時

/*---------------------------------------*   日期:2015-06-30*   作者:SJF0115*   題目:整數分隔*   來源:華為上機-----------------------------------------*/#include <iostream>#include <string>#include <algorithm>#include <vector>using namespace std;#define Max 1000000int Split(int n){    if(n == 1){        return 1;    }//if    if(n == 2){        return 2;    }//if    // 奇數    if(n % 2){        return Split(n-1) % 1000000000;    }//if    else{        return Split(n-2) % 1000000000 + Split(n/2) % 1000000000;    }//else}int main(){    int n;    //freopen("C:\\Users\\Administrator\\Desktop\\c++.txt","r",stdin);    while(cin>>n){        if(n > Max){            return -1;        }//if        cout<<Split(n)<<endl;    }//while    return 0;}

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.