PAT數據結構陳越——自測04

最近在看網易雲課堂的浙大數據結構公開課視頻。跟着做了一些基礎的習題。這是其中一道。
題目如下:

00-自測4. Have Fun with Numbers (20)

時間限制
400 ms
內存限制
65536 kB
代碼長度限制
8000 B
判題程序
Standard
作者
CHEN, Yue
Notice that the number 123456789 is a 9-digit number consisting exactly the numbers from 1 to 9, with no duplication. Double it we will obtain 246913578, which happens to be another 9-digit number consisting exactly the numbers from 1 to 9, only in a different permutation. Check to see the result if we double it again!

Now you are suppose to check if there are more numbers with this property. That is, double a given number with k digits, you are to tell if the resulting number consists of only a permutation of the digits in the original number.

Input Specification:

Each input file contains one test case. Each case contains one positive integer with no more than 20 digits.

Output Specification:

For each test case, first print in a line “Yes” if doubling the input number gives a number that consists of only a permutation of the digits in the original number, or “No” if not. Then in the next line, print the doubled number.

Sample Input:
1234567899
Sample Output:
Yes
2469135798
題目是英文的,我簡單翻一下。。
簡單說就是一個最多20位的數字,乘上2倍,得出的數字是否和原來的數字構成是一樣的,比如原來是123456789,乘上2後=246913578還是由123456789這9個數字組成的數,只是順序變了。如果輸入的數字滿足上面的要求就輸出Yes,否則輸出No,並輸出x2後的結果。
因爲最多有20位的數字,就不能簡單用int或long計算,要用字符數組模擬乘法的計算,將輸入的數每一位x2+進位得到結果。具體代碼如下:

int main() {
    //記錄輸入正整數的數字組成
    int zc[10] = {0};
    //因爲不知道長度所以先讀取成字符串
    char input_str[25];
    cin>>input_str;
    //獲得字符串長度
    int length = strlen(input_str);
    int num[25];
    int i;
    //字符數組轉換成int數組,並賦值記錄數組
    for(i=0;i<length;i++) {
        num[i] = input_str[length-i-1]-'0';
        zc[num[i]]++;
    }
    //for(i=0;i<10;i++) cout<<zc[i]<<" "; 
    //把原來的數字x2
    int c = 0;
    for(i=0;i<length;i++) {

        int s = num[i]*2+c;
        num[i] = s%10;
        c = s/10;
    }
    if(c!=0) {
        num[length]=c;
        length++;
    }
    for(i=0;i<length;i++) {
       zc[num[i]]--;
    }
    bool isOk=true;
    for(i=0;i<10;i++) {
        if(!zc[i]==0) isOk=false;
    }
    for(i=length-1;i>=0;i--) cout<<num[i];
    cout<<endl;
    if(isOk) cout<<"YES";
    else cout<<"NO";
    cout<<endl;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章