2012/02/29

[zerojudge] d086 態度之重要的證明

題目:https://zerojudge.tw/ShowProblem?problemid=d086
說明:先將字元全部轉成大寫,然後判斷其 ASCII 碼是否落在字母的範圍,若不是則表示不是字母,若是就將其數字減去 64 後計算總和。

Java 版
import java.util.Scanner;

public class D086 {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String input = in.nextLine();
            if(input.equals("0"))
                break;
            int sum = 0;
            char [] chars = input.toUpperCase().toCharArray();
            boolean fail = false;
            for (char c : chars) {
                if ((int) c < 65 || (int) c > 90) {
                    fail = true;
                    System.out.println("Fail");
                    break;
                } else {
                    sum += ((int) c - 64);
                }
            }
            if (!fail)
                System.out.println(sum);
        }
    }
}
Python 版 (2022.07)
while True:
    try:
        a = input()
        if a == '0':
            break
        cs = list(a)
        s = 0
        fail = False
        for c in cs:
            n = ord(c.upper())
            if n < 65 or n > 90:
                fail = True
                print('Fail')
                break
            else:
                s += (n - 64)
        if not fail:
            print(s)
    except:
        break

沒有留言:

張貼留言