首页 > 试题广场 >

A+B Format (20)

[编程题]A+B Format (20)
  • 热度指数:3926 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
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).

输入描述:
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
import java.util.Scanner;
//没什么难点,从第一位开始输出字符。
//count计数,每输出了三个字符(且不为最后一个字符)就输出一个“,”
public class Main {

	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
		long a=in.nextLong();
		long b=in.nextLong();
		long c=a+b;
		
		if(c<0){
			System.out.print("-");
			c=0-c;
		}
		
		String s=String.valueOf(c);
		String out="";
		int count=0;
		for(int i=s.length()-1;i>=0;i--){
			out=s.charAt(i)+out;
			count++;
			if(count%3==0&&i!=0){
				count=0;
				out=","+out;
			}
			
		}System.out.println(out);
	}

}


发表于 2016-10-27 19:54:13 回复(0)
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));

			} else
				break;
			index -= 3;
		}
		res.insert(0, sum.substring(0, index + 3));
		System.out.println(res);
		sc.close();
	}
}


发表于 2017-08-22 10:37:44 回复(0)
// 差点忘了判断边界,
//而且第一次代码错了,竟然也过了(/ w\)
//蓝后用栈再做了一下~~^_-
#include <iostream>
#include <string>
#include <set>
#include <algorithm>
#include <iomanip>
#include <cstdio>
#include <vector>
#include <stdlib.h>
#include <stack>
#include <deque>
#include <cstring>
using namespace std;
#define Mod 1000000007

void  slove(int x);
int main()
{
    int a, b, ans;
    cin>>a>>b;
    ans=a+b;
    slove(ans);
    return 0;
}
void slove(int x){
    if(x==0) {cout<<"0"<<endl;return ;}
    if(x<0){cout<<"-"; x=-x;}
    stack<int>s;
    while(x){
        int t=x%10;
        s.push(t);
        x/=10;
    }
    while(!s.empty()){
        cout<<s.top();
        s.pop();
        int len=s.size();
        if(len%3==0&&len) cout<<",";
    }
    cout<<endl;
}  

发表于 2015-07-16 21:16:21 回复(0)
一个个代码那么长 我发个短一点的纯C语言版
  1. #include <stdio.h>
  2. void print(int a){
  3.     if(a > 1000){
  4.         print(a / 1000);
  5.         printf(",%d",a % 1000);
  6.     } else
  7.         printf("%d",a);
  8. }
  9. int main(){
  10.     int a ,b;
  11.     if(scanf("%d%d",&a ,&b));
  12.     a += b;
  13.     if(a < 0){
  14.         printf("-");
  15.         a *= -1;
  16.     }
  17.     print(a);
  18.     return 0;
  19. }
编辑于 2018-06-26 17:35:50 回复(1)
读整数然后做加法是没有问题的,然后就是数字字符串加逗号,这个可以用正则表达式搞定。
用零宽断言,就一行代码:
String.valueOf(value).replaceAll("(?<=\\d)(?=(\\d\\d\\d)+)", ",")

编辑于 2018-01-06 23:14:22 回复(0)
#include<stdio.h>
int main()
{
	int x, y;
	while (~scanf("%d%d", &x, &y))
	{
		int sum = x + y;
		if (sum < 0)
		{
			printf("-");
			sum = -sum;
		}
		if (sum<1000 && sum>-1000)
			printf("%d\n", sum);
		else if (sum<1000000 && sum>-1000000)
			printf("%d,%03d\n", sum / 1000, sum % 1000);
		else
			printf("%d,%03d,%03d\n", sum / 1000000, sum / 1000 - 1000 * (sum / 1000000), sum % 1000);
	}
	return 0;
}

发表于 2017-08-04 23:21:34 回复(0)
#include<bits/stdc++.h>
using namespace std;

int main() {
	int a,b;
	cin>>a>>b;
	int c=a+b;
	if(c<0) cout<<'-';
	string s=to_string(abs(c)),answer;
	reverse(s.begin(),s.end());
	for(int i=s.size()-1; i>=0; i--) {
		cout<<s[i];
		if(i>0&&i%3==0) cout<<',';
	}
	return 0;
}

发表于 2022-11-07 17:31:35 回复(1)
#include<iostream>
using namespace std;
int main(){
    int a,b,sum;
    int num[10];   //倒序存储和的绝对值的数组
    cin>>a>>b;
    sum=a+b;
    if(sum<0){
        cout<<"-";
        sum=-sum;
    }
    int i;
    for(i=0;sum>0;i++){
        num[i]=sum%10;
        sum/=10;
    }
    for(int j=i-1;j>=0;j--){
        cout<<num[j];
        if(j%3==0&&j!=0)
            cout<<",";
    }
    return 0;
}


编辑于 2021-08-16 20:21:47 回复(0)
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main() {
    int a,b,c;
    cin >> a >> b;
    c=a+b;
    if(c>=-999 && c<=999) cout << c;
    else{
        if(c<0) cout << "-";
        c=max(c,-c);
        vector<char> ans;
        int flag=0;
        while(c){
            int tmp=c%10;
            if(flag==3){
                flag=0;
                ans.push_back(',');
            }
            ans.push_back(tmp+'0');
            flag++;
            c=c/10;
        }
        for(int i=ans.size()-1;i>=0;i--)
            cout << ans[i];
    }

    return 0;
}

发表于 2021-08-07 21:32:19 回复(0)
#include<stdio.h>
int main(){
    int a, b, sum, flag = 0, i = 0, count, count1 = 0;
    char c[1000000];
    scanf("%d %d", &a, &b);
    sum = a + b;
    if(sum==0){
        printf("0");
        return 0;
    }//PTA里的测试点,其他没有要注意的
    if(sum<0){
        flag = 1;
        sum *= -1;
    }
    while(sum){
        c[i++= sum % 10 + '0';
        sum /= 10;
        count1++;
        if(count1==3&&sum){
            c[i++= ',';
            count1 = 0;
        }
    }
    if(flag==1){
        c[i++= '-';
    }
    count = i;
    for (i = count-1; i >= 0;i--){
        
        printf("%c", c[i]);
    }
    return 0;
}
发表于 2021-02-05 22:59:36 回复(0)
水水水水水水
print("{:,}".format(sum(map(int,input().split()))))

发表于 2020-02-19 11:39:31 回复(0)
#include<iostream>
#include<vector>
#include<string.h>
#include<map>
#include <string>
using namespace std;
void aplusbformat() {
	long long a, b;
	vector<long long>q;
	cin >> a >> b;
	a += b;
	if (a < 0) {
		cout << "-";
		a = -a;
	}
	else if (a == 0) {
		cout << "0";
	}
	 while (a != 0) {
		q.push_back(a%10);//
		a /= 10;
	}
	vector<string> qp;
	auto it = q.begin();
	int i1 = 0;
	while (it != q.end()) {
		if (i1 != 0&&i1 % 3 == 0) {
			qp.push_back(",");
		}
		i1++;
		string s = to_string(*it);
		qp.push_back(s);
		it++;
	}
	while (qp.size() != 0) {
		cout << qp.back();
		qp.erase(qp.end()-1);
	}
}
//-1000000 9
int main()
{
	aplusbformat();
	return 0;
}

发表于 2020-01-26 22:32:39 回复(0)

#include <iostream>

#include <string>

using namespace std;

int main() {

//第一种方法

    int a, b, c;

    string s;

    cin>>a>>b;

    c = a + b;

    s = to_string(c);// to_string 将数值转化为字符串。返回对应的字符串。

    int n = s.size();

    int temp = 0;

    if (c < 0) temp = 1;

    for (int i = n - 3; i > temp; i -= 3) {

        s.insert(i, ",");// s.insert(pos, str),pos是待插入的位置, str是待插入的字符串

    }

    cout << s << endl;

//第二种方法

    int k[8],i=0,flag=0;//建立数组,两个七位数相加最多八位数,所以选择k[8]

    if(c<0){

        c=-c;

        flag=1;

    }

    if(c==0)cout<<"0";

    else{

        while(c)

        {

            k[7-i]=c%10;

            c=c/10;

            i++;

        }

        if(flag)cout<<"-";

        for(i=8-i;i<8;i++)//8-i为该数组的起始位置

        {

            cout<<k[i];

            if(i==1||i==4)

                cout<<",";

        }

    }

    return 0;

}

发表于 2019-08-04 10:04:23 回复(0)
import java.util.Scanner;
public class Main{
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int a = scanner.nextInt();
int b = scanner.nextInt();
String c = String.valueOf(a + b);
StringBuilder s = new StringBuilder();
int flag = 0;
for (int i = c.length() - 1; i >= 0 ; i--) {
s.append(c.charAt(i));
flag++;
if (flag % 3 == 0){
s.append(',');
}
}
String x = s.reverse().toString();
x = x.replace("-,","-");
if (x.startsWith(",")){
x = x.substring(1);
}
System.out.println(x);
}
}

发表于 2019-07-13 23:41:29 回复(0)
python两行搞定
m,n=map(int,raw_input().split())
print format(m+n,',')
发表于 2019-01-16 15:57:33 回复(0)
a,b = map(int,input().split())
c = str(a + b)
lsc= []
for i in c:
    lsc.append(i)
cnt = 0
lsout = []
for i in range(len(lsc)-1,-1,-1):
    if lsc[i]>='0' and lsc[i]<='9':
       cnt+=1
if cnt>6:
   lsout = lsc[:len(lsc)-6]+[","]+lsc[len(lsc)-6:len(lsc)-3]+[',']+lsc[len(lsc)-3:]     
elif cnt>3:
    lsout = lsc[:len(lsc)-3]+[',']+lsc[len(lsc)-3:]   
out = ''
for i in lsout:
    out = out + i
if out!='':
    print(out)
else:
    for i in lsc:
        out = out + i
    print(out)

发表于 2018-11-25 20:40:28 回复(0)
#include <iostream>
#include <vector>

using namespace std;

vector<int> divided_sum;

int main()
{     int a, b;     cin >> a >> b;     int sum = a + b;     if (sum < 0) {         cout << "-";         sum = -sum;     }     if (sum == 0) {         cout << "0";     } else {         int temp = 0;         while (sum != 0) {             temp = sum % 1000;             divided_sum.push_back(temp);             sum = sum / 1000;         }         for (int i = divided_sum.size() - 1; i >= 1; i--) {             cout << divided_sum[i] << ",";         }         cout << divided_sum[0];     }              system("pause");     return 0;
}

发表于 2018-08-20 23:06:53 回复(0)
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
// 思路: 题目的意思就是A+B 然后输出C,C有一定的格式,每大于3个数要输出一个“,”
// 个人的思路就是先给一个count 赋初值。如果这个初值为1 就是把纯数字的部分凑层3的倍数这样才能从大到小的添加“,”
// That's all,Thinks!
int main(int argc, char** argv) {
    long A;
    long B;
    cin >> A >> B;
    long C = A + B;
    stringstream ss;
    ss << C;
    string C2;
    ss >> C2;
    int count = 0;
    int i = 0;
    if(C<0){
        cout<< "-";
        i = 1;
    }
    count = 3 - (C2.size()-i) % 3;
    if(count == 3)
        count = 0;
    for(; i<C2.size(); i++)
    {
        count ++;
        cout << C2[i];
        if(count >= 3 && i != C2.size() - 1)
        {
            cout << "," ;
            count = 0;
        }
    }
    cout << endl;
    //while(1);
    return 0;
     
}

发表于 2018-07-16 11:17:53 回复(0)
#include <cstdio>
int main()
{
    int a,b,i;
    int A[10]={0};
    scanf("%d %d",&a,&b);
    a=a+b;
    if(a==0)
    {
        printf("0");
        return 0;
    }
    else if(a<0)
    {
        printf("-");
        a=-a;
    }
    for(i=0;a!=0;i++)
    {
        A[i]=a%10;
        a=a/10;
    }
    for(i-=1;i>=0;i--)
    {
        printf("%d",A[i]);
        if(i%3==0&&i!=0)
            printf(",");
    }
    return 0;
}
请注意了,由于测试用例有一些不同,在牛客网提交时不判断a+b的结果为0的情况时也可以通过测试用例,但在PAT中提交必须判断a+b等于0的情况,否则会有一个测试点不通过。

发表于 2018-06-06 09:03:06 回复(0)
#include <iostream>
#include <string>
using namespace std;
int main()
{
	long A,B,sum;
	bool flag=false;
	cin>>A>>B;
	char num[]={'0','1','2','3','4','5','6','7','8','9'};
	string str="";
	int i=0;
	sum=A+B;
	if(sum<0)
	{
		sum=-sum;
		flag = true;
	}		
	while(sum)
	{
		i++;
		str = num[sum%10] + str;
		sum /=10;
		if((i%3)==0 && sum!=0)
			str ="," + str;
	}
	if(flag)
		str ="-" + str;
	cout<<str;
	return 0;
}

编辑于 2017-08-16 08:12:48 回复(0)