iT邦幫忙

2021 iThome 鐵人賽

DAY 25
0
自我挑戰組

用 C & C++ 帶你手把手解 UVa 一顆星選集系列 第 25

Day 0x19 UVa10929 You can say 11

題意

  • 輸入一整數,判斷是否為 11 的倍數
  • 需要注意的有:
    1. 重複輸入一整數 N 直到 0
    2. N 最大可到 1000 位
    3. 輸出格式
      • N is a multiple of 11.
      • N is not a multiple of 11.

解法

  • 如何快速判斷一個數是不是 11 的倍數?
  • 重複輸入一字串 n (因為整數存不下) 直到 0
    char n[1000] = {0};
    
    while(scanf("%s", n)){
        if(*n == '0' && strlen(n) == 1){
            break;
        }
        else{
            ...
        }
    }
    
  • 透過 for 迴圈及迴圈變數 i 控制一加一減每個位數,要記得是字元所以要 - '0'
    int i;
    int difference = 0;
    
    for(i = 0; i < strlen(n); i++){
        if(i % 2 == 0){
            difference = difference + (n[i] - '0');
        }
        else{
            difference = difference - (n[i] - '0');
        }
    }
    
  • 最後判斷是否為 11 的倍數再輸出結果
    if(difference % 11 == 0){
        flag = true;
    }
    
    if(flag){
        printf("%s is a multiple of 11.\n", n);
    }
    else{
        printf("%s is not a multiple of 11.\n", n);
    }
    
  • C code
    #include<stdio.h>
    #include<string.h>
    #include<stdbool.h>
    
    int main(){
    
        char n[1000] = {0};
    
        while(scanf("%s", n)){
            if(*n == '0' && strlen(n) == 1){
                break;
            }
            else{
    
                int i;
                bool flag = false;
                int difference = 0;
    
                for(i = 0; i < strlen(n); i++){
                    if(i % 2 == 0){
                        difference = difference + (n[i] - '0');
                    }
                    else{
                        difference = difference - (n[i] - '0');
                    }
                }
    
                if(difference % 11 == 0){
                    flag = true;
                }
    
                if(flag){
                    printf("%s is a multiple of 11.\n", n);
                }
                else{
                    printf("%s is not a multiple of 11.\n", n);
                }
            }
        }
    
        return 0;
    }
    

上一篇
Day 0x18 UVa10415 Eb Alto Saxophone Player
下一篇
Day 0x1A UVa10931 Parity
系列文
用 C & C++ 帶你手把手解 UVa 一顆星選集30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言