2017年9月25日 星期一

[UVa]10929 - You can say 11(C++)

找出11的倍數,此數字的奇數位數的和簡偶位數的和相減的絕對值,為11的倍數則此數是11的倍數,反之則否。
5038297 :
奇數 : 7 + 2 + 3 + 5 = 17
偶數 : 9 + 8 + 0 = 17
|奇數 - 偶數| = 0
5038297是11的倍數

  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. int main() {  
  5.     string s;  //待測數字
  6.     while(cin >> s && s != "0")  //使用者輸入s,且s不能為0
  7.     {  
  8.         long long sum[2] = {0, 0};   //放奇數和和偶數和的陣列
  9.         for(int i = 0;i < s.length();i++)    
  10.         {  
  11.             sum[i%2] = sum[i%2] + s[i] - '0';  
  12.         }  
  13.         if(abs(sum[0]-sum[1])%11 == 0)  
  14.         {  
  15.             cout << s << " is a multiple of 11." << endl;  
  16.         }else  
  17.         {  
  18.             cout << s << " is not a multiple of 11." << endl;  
  19.         }  
  20.     }  
  21.     return 0;  
  22. }  

沒有留言:

張貼留言