Python實現Pat 1065. A+B and C (64bit) (20)

題目描述

Given three integers A, B and C in [-263, 263), you are supposed to tell whether A+B > C.

輸入描述:
The first line of the input gives the positive number of test cases, T (<=1000). Then T test cases follow, each consists of a single line containing three integers A, B and C, separated by single spaces.

輸出描述:
For each test case, output in one line “Case #X: true” if A+B>C, or “Case #X: false” otherwise, where X is the case number (starting from 1).

輸入例子:
3
1 2 3
2 3 4
9223372036854775807 -9223372036854775808 0

輸出例子:
Case #1: false
Case #2: true
Case #3: false

解答

用C或c++語言實現起來比較麻煩,要考慮溢出問題:(參考的博客
1.long long 取值爲【-2^63, 2^63)左開右閉。
2.超出範圍的時候要判斷溢出情況,考慮溢出後的取值
3.A+B的值必須用long long 類型 的res存儲後才能與C進行比較,不能直接放到if()中進行比較不然測試點2、3過不去。
4.分情況判斷時候要用else if 不能一串if,不然可能會出現一種情況滿足幾個條件,造成後面的flag覆蓋前面的(正負溢出應該優先判斷)

而用Python就非常簡單了。而且也能通過測試。

n=int(input())
for i in range(n):
    abc=[int(x) for x in input().split(' ')]
    if abc[0]+abc[1]>abc[2]:
        print("Case #%d: true"%(i+1))
    else:
        print("Case #%d: false" % (i+1))

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章