[Python/Java](PAT)1001 A+B Format (20)
阿新 • • 發佈:2019-01-01
Calculate a+b and output the sum in standard format -- that is, the digits must be separated into groups of three by commas (unless there are less than four digits).
Input Specification:
Each input file contains one test case. Each case contains a pair of integers a and b where −106≤a,b≤106. The numbers are separated by a space.
Output Specification:
For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.
Sample Input:
-1000000 9
Sample Output:
-999,991
題目大意
計算輸入的A和B的和,按照每三位以','分割的格式輸出
把a+b的和轉為字串s。除了第一位是負號的情況,只要當前位的下標i滿足(i + 1) % 3 == len % 3並且i不是最後一位,就在逐位輸出的時候在該位輸出後的後面加上一個逗號。
分析
使用python實現就直接相加然後格式化輸出就可以了。
使用java實現,則先判斷相加後是否是負數。是負數先輸出負號。然後倒置字串,每隔三個字元加一個逗號,且如果處於最後的位置則不用新增逗號。最後再翻轉過來,輸出即可。
python實現
if __name__ == "__main__":
line = input().split(" ")
a, b = int(line[0]), int(line[1])
print('{:,}'.format(a+b))
java實現
import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] line = br.readLine().split(" "); br.close(); int temp = Integer.valueOf(line[0]) + Integer.valueOf(line[1]); if(temp < 0){ System.out.print("-"); } String s = String.valueOf(Math.abs(temp)); String a = new StringBuffer(s).reverse().toString(); String get = ""; for(int i=0;i<a.length();i++){ get = get + a.charAt(i); if((i+1) %3 == 0 && i != a.length() - 1){ get = get + ','; } } String out = new StringBuffer(get).reverse().toString(); System.out.print(out); } }
通過這個例子可以看出,如果不想用C/C++來寫PAT的話,python也勉強可以考慮用來解題,但是java真的太慢了