迴文數

 迴文數


Time Limit:1 Ms| Memory Limit:64 MB
Difficulty:2

Description

 若一個數(首位不爲零)從左向右讀與從右向左讀都一樣,我們就將其稱之爲迴文數。
  例如:給定一個10進制數56,將56加65(即把56從右向左讀),得到121是一個迴文數。

  又如:對於10進制數87:
  STEP1:87+78 = 165 STEP2:165+561 = 726
  STEP3:726+627 = 1353 STEP4:1353+3531 = 4884

  在這裏的一步是指進行了一次N進制的加法,上例最少用了4步得到迴文數4884。

  寫一個程序,給定一個N(2<=N<=16)進制數M(其中數字爲0-9大於,10進制的字母爲A-F),求最少經過幾步可以得到迴文數。
  如果在40步以內(包含40步)不可能得到迴文數,則輸出“Impossible!”

Input

兩行,N與M

Output

如果能在40步以內得到迴文數,輸出“STEP=xx”(不含引號),其中xx是步數;否則輸出一行”Impossible!”(不含引號)

Sample Input

9
87

Sample Output

STEP=6

Hint

M < 20位
#include<stdio.h>
#include<string.h>
char str[30];
int cal[30];
int ans[30];
int base;
  
int judge(int len){
    int i, j;
/*判斷迴文*/
  for(i = 0, j = len - 1; i <= len / 2; i++, j--){
        if(cal[i] != cal[j])
            return 0;
    }
    return 1;
}
  
int main(){
    int step = 0;
    int i, j, count;//ans's count
    scanf("%d", &base);
    scanf("%s", &str);
      
    int len = strlen(str);
    for(i = 0; i < len; i++){//change to nubmer
        if(str[i] >= 'A' && str[i] <= 'F'){
            cal[i] = str[i] - 'A' + 10;      
        }
        if(str[i] >= '0' && str[i] <= '9')
            cal[i] = str[i] - '0'; 
    }
      
    if(judge(len)){
        printf("STEP=0\n");
    }
    else
    {
        while(step <= 40){
            memset(ans, 0, sizeof(ans));    
            step++;     
              
            for(i = 0, j = len -1; i < len ;i++, j--){//plus
                int tmp, carry;
                tmp = cal[i] + cal[j] + ans[i];//無需翻轉直接相加
                if(tmp >= base){ //這裏有點類似於大數            
                    ans[i] = tmp - base;
                    ans[i+1] = 1;     
                }
                else
                    ans[i] = tmp;           
            }
            if(ans[len] == 1)
                len = len + 1;
                          
            for(i = 0; i < len; i++)
                cal[i] = ans[i];
            if(judge(len)){
                printf("STEP=%d\n", step);
                break;
            }
            else
                continue;       
        }
        if(step > 40){
            printf("Impossible!\n");
        }   
    }     
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章