[PAT甲级]1001 A+B Format (20 分)

题目

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

分析

水题,转换成字符串输出,考虑临界值为0的情况即可!

代码


#include<iostream>

#include<cmath>

#include<string>

using namespace std;

int main(){

    int a,b;

    cin>>a>>b;

    int x=a+b;

    if(x==0){

        cout<<0<<endl;

        return 0;

    }

    int flag=0,i=1;

    string str="";

    if(x<0) flag=1;

    x = abs(x);

    while (x>0) {

        str = char(x%10+'0') + str ;

        if(i%3==0 && x>=10)

            str = ',' + str ;

        x=x/10;

        i++;

    }

    if(flag==1) str='-'+str;

    cout<<str<<endl;

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 13,233评论 0 13
  • “我明明什么都没做,就已经……” 这句年前很火的话,想想触目惊心。时间真的自己溜走了吗? 我在更新这篇文章之前,我...
    程小姑娘阅读 4,492评论 0 2
  • 之前对于体验我总觉得是经历或者参与,比如看电影,比如散步,比如旅行……但最近读了《对生命说是》这本书,我才懂得体验...
    简单_c3d4阅读 5,842评论 0 2
  • 傍晚时分,天降大雨。
    999439e28bf0阅读 1,765评论 0 0
  • 爱一个人,究竟能有多深?七月和安生告诉了我们,不过是在那个人离开了以后,活成了对方的模样。 安生说...
    樱阳阅读 2,929评论 0 0

友情链接更多精彩内容