1001 A+B Format (20point(s))(Java和C++)
生活随笔
收集整理的這篇文章主要介紹了
1001 A+B Format (20point(s))(Java和C++)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- Java版
- C++版
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 ?10?6
?? ≤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:
Sample Output:
-999,991一開始做題的時候搞錯了一個點,導致測試點一半正確,一半錯誤:就是從前往后每3個數出一個逗號。就像給的測試用例一樣,但是這種方法只對字符串長度是3的整數倍的sum有效,要改成從后往前每3個數輸出一個逗號
用一個特殊情況舉例:
1000000+1000000=2000000
Java版
//20分 import java.io.*; import java.math.BigInteger;public class Main {public static void main(String[] args) throws IOException {//定義輸入BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));//輸入兩個整數String[] str = bf.readLine().split("\\s+");//將輸入的字符串轉化為BigInteger類型BigInteger a = new BigInteger(str[0]);BigInteger b = new BigInteger(str[1]);//計算兩個整數加和并轉化為String類型String sum = a.add(b) + "";//如果結果是負數,輸出“-”,之后將字符串中的“-”去掉if (sum.charAt(0) == '-') {System.out.print("-");sum = sum.substring(1);}//遍歷新字符串for (int i = 0; i < sum.length(); i++) {System.out.print(sum.charAt(i));//(i + 1) % 3 == sum.length() % 3是用來判斷逗號要加的位置//(i != sum.length() - 1))用來保證輸出的最后一位不輸出逗號if ((i + 1) % 3 == sum.length() % 3 && (i != sum.length() - 1)) {System.out.print(",");}continue;}} }C++版
//參考柳神代碼 //沒想到思路和我的一樣 🤭 #include <iostream> #include<cstdio>using namespace std;int main() {int a, b;scanf("%d %d", &a, &b);string s = to_string(a + b);for (int i = 0; i < s.length(); i++) {cout << s[i];if (s[i] == '-')continue;if ((i + 1) % 3 == s.length() % 3 && i != s.length() - 1)cout << ",";}return 0; }總結
以上是生活随笔為你收集整理的1001 A+B Format (20point(s))(Java和C++)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 张朝阳再谈四小时睡眠法:不能睡7个小时
- 下一篇: 爱因斯坦100多年前广义相对论的“引力透