2017年6月12日 星期一

CPE 005 UVa10929-You can say 11


題目原文
題目內容
你的任務是,給你一個正整數 N,判定它是否是 11 的倍數。

輸入說明:
每列資料有一個正整數N,N 最大可能到 1000 位數。
若 N = 0 代表輸入結束

輸出說明:
對每個輸入的數,輸出是否為 11 的倍數。輸出格式請參考 Sample Output。

Sample Input

112233
30800
2937
323455693
5038297
112234
0

Sample Output

112233 is a multiple of 11.
30800 is a multiple of 11.
2937 is a multiple of 11.
323455693 is a multiple of 11.
5038297 is a multiple of 11.
112234 is not a multiple of 11.


解法
使用之前數學所教的奇數位的和跟偶數位的和相減看是不是11的倍數,此題建議用讀字串的方式讀入資料。
(以上資料來源:大學程式能力檢定Collegiate Programming Examination(CPE))




程式碼解答


#include <stdio.h>
#include <string.h>
int main()
{
 char number[1001];
 while (scanf("%s", number)!=EOF)
 {
  
  int i;
  long int length=strlen(number);///讀出字串長度
  if(length==1 && number[0]=='0')///判斷是否只有一個位數並且輸入的該數不能為零 
   break;
  int odd=0, even=0;
  for(i=0; i<length; i++)///分別做奇偶數位的相加
  {
   if(i%2==0)
    odd=odd+(number[i]-'0');
   else
    even=even+(number[i]-'0');
  }
  if((odd-even)%11==0)//判斷
   printf("%s is a multiple of 11.\n", number);
  else
   printf("%s is not a multiple of 11.\n", number); 
  
 }
 
 
}




程式碼打包:解法一

沒有留言:

張貼留言