栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

PAT 1001 A+B Format (20 分) Java题解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

PAT 1001 A+B Format (20 分) Java题解

PAT 1001 A+B Format (20 分) Java题解

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
结尾无空行

代码如下:

package advanced;

import java.util.Scanner;


public class Question1001 {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        int c = a + b;
        int temp = Math.abs(c);
        if (c < 0){
            System.out.print("-");
        }
        String answer = String.valueOf(temp);
        for (int i = 0; i < answer.length(); i++) {
            System.out.print(answer.charAt(i));
            if ((i + 1) % 3 == answer.length() % 3 && i != answer.length() - 1){
                System.out.print(",");
            }
        }
    }
}

思路

step1:将计算结果转成字符串

step2:将字符串遍历输出

在输出时,如果索引 i 的值满足(i + 1) % 3 == answer.length() % 3 && i != answer.length() - 1则输出一个“,”号,第一个条件(i + 1) % 3 == answer.length() % 3保证了“,”号是每个三个输出,又因为每个三的逗号输出时从末尾数,每三个输出逗号,为了保证每次位移程度都相同,所以等式左边应该是answer.length() % 3

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/658355.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号