1001 A+B Format (20 分)

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≤10​6​​. 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

思路:如果我们从整数这个思路来求的话,我们需要知道这个数的长度,通过求模,得到长度,然后对这个数从高位到低位求,总长度减去当前所处位置是不是3的倍数,。这样比较麻烦,有没有求出这个数将其转为字符串的函数呢?有的 ,这篇博文写了一些转化的方式:https://blog.csdn.net/qq_40511966/article/details/81010855。如果把这个数换成字符串就很好处理了,<=三位的直接输出,超过三位的总长度减去当前所处位置是不是3的倍数,是则输出一个逗号(如,总长7(1234567),当前位置0,很明显不是3的倍数,当前位置1,7-1是3 的倍数,故而输出一个,需要注意的是0也是3的倍数)。由于我代码的原因,我还需要判断i==0也不能输出,why?如果总长9位,它首先输出一个,。

c++

#include<iostream>
#include<string>
#include<sstream>
using namespace std;


int main()
{
	int a,b,sum;
	string s;
	cin >> a >> b;
	stringstream ss;
	sum = a+b;
	if(sum < 0)
	{
		sum = sum*(-1);
		cout << "-";
	} 
	ss << sum;
	ss >> s;
	if(s.length()<=3)
	   cout << s << endl; 
	else
	{
		for(int i = 0;i < s.length();++i)
		{
			if((s.length()-i)%3 == 0 && i != s.length()-1 && i != 0)
			  cout << ",";
			 cout << s[i]; 
		}
		cout << endl;
	} 
	return 0;
}

Java(仅提供写法,不提供oj版)

public class Main{

    public static void getResult(String sum){

        int len = sum.length();
        char[] str = sum.toCharArray();
        for(int i = 0;i < len;++i)
        {
            if((len-i)%3 == 0 && i != len-1 && i != 0)
            {
                System.out.print(",");
            }
            System.out.print(str[i]);
        }

    }
    public static void main(String[] args){
             int a,b;
             Scanner in = new Scanner(System.in);

             a = in.nextInt();
             b= in.nextInt();
             Integer sum = a+b;
             if(sum < 0)
             {
                 sum *= -1;
                 System.out.print("-");
             }


             getResult(sum.toString());
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值