[PAT]1001 A+B Format (20)

来源:互联网 发布:人工智能与机器人关系 编辑:程序博客网 时间:2024/06/05 16:12

链接:https://www.nowcoder.com/questionTerminal/30ebf35cea7f4e8398dd0f12c069dc76

来源:牛客网

[编程题]A+B Format (20)
  • 热度指数:743时间限制:1秒空间限制:32768K
  • 算法知识视频讲解
Calculate a + b and output the sum in standard format -- that is, thedigits must be separated into groups of three by commas (unless thereare less than four digits).
输入描述:
Each input file contains one test case.  Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000.  The numbers are separated by a space.


输出描述:
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.
示例1

输入

-1000000 9

输出

-999,991

知识点:StringBuilder要在字符串前插入元素,用insert()方法


package go.jacob.day822;import java.util.Scanner;/** * 1001. A+B Format (20) *  * @author Jacob * 思路:从后往前遍历,每个三位加","。同时要考虑前一位是否为"-"和总位数是否小于4 */public class Demo2 {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int a = sc.nextInt(), b = sc.nextInt();String sum = a + b + "";int index = sum.length() - 3;StringBuilder res = new StringBuilder();while (index > 0) {if (sum.charAt(index - 1) != '-') {res.insert(0, "," + sum.substring(index, index + 3));} elsebreak;index -= 3;}res.insert(0, sum.substring(0, index + 3));System.out.println(res);sc.close();}}


原创粉丝点击