APCS 2017-0304-1秘密差

問題描述:

將一個十進位正整數的奇數位數的和稱為A ,偶數位數的和稱為B,則A與B的絕對差值 |A -B| 稱為這個正整數的秘密差。 例如: 263541 的奇數位和 A = 6+5+1 =12,偶數位的和 B = 2+3+4 = 9 ,所以 263541 的秘密差是 |12 -9|= 3 。 給定一個 十進位正整數 X,請找出 X的秘密差。

Sample input1: 263541    Sample output1: 3

Sample input2: 131           Sample output2: 1

Thought:

Using a char array to read the input as a string makes it easier to access each digit directly using indexing. This avoids the need for operations like num % 10 and num / 10, which would be necessary if you read the input as an integer.


/*
c290. APCS 2017-0304-1秘密差
https://zerojudge.tw/ShowProblem?problemid=c290
*/

#include
#include

int main() {
    char arr[1000];
    scanf("%s", arr);
    int len = strlen(arr);
    int odd = 0;
    int even = 0;
    for (int i = 0; i < len; i++) {
        int num = arr[i] - '0';
        if (i % 2 == 0) { // Even
            even+=num;
        } else { // Odd
            odd+=num;
        }
    }
    int ans = even - odd;
    if (ans < 0) {
        ans*=-1;
    }
    printf("%d", ans);
    return 0;
}
            
Problem Source

My Solution

GitHub