PAT (Advanced Level) Practice 1001 A+B Format

题目链接:PTA | 程序设计类实验辅助教学平台

题目大意:输入两个数(范围int就够了),输出他们的和,要求右数每三位用一个comma就是逗号隔开。

一开始做的:

用string记录每一位。

1.注意负数是每次取余得到的是负数,所以一开始abs一下

2.最后记得补上负号输出

3.记得考虑0的情况,测试点4

#include<bits/stdc++.h>
using namespace std;

int a, b, c, cnt = 1 ;
string s;

int main(){
    cin >> a >> b;
    c = abs(a + b);
    while( c ){
        s += ( c%10 + '0' );
        if( cnt % 3 == 0 && c > 9 )    s += ',';
        cnt ++ , c /= 10;
    }
    if( a+b < 0 )    cout << "-";
    if( a+b == 0 )    cout << 0 ;
    for( int i = s.length()-1 ; i >= 0 ; i -- )    cout << s[i];
    cout << endl;
}

后面想到用to_string()

#include<bits/stdc++.h>
using namespace std;

int a, b, len;
string s;

int main(){
    cin >> a >> b;
    s = to_string(a+b);
    len = s.length();
    for( int i = 0; i < len; i ++ )
        cout << s[i] << ( (len-i-1) % 3 == 0 && s[i] != '-' ? ( i == len - 1 ? "\n" : ",") : "" ) ;
}

10行ac

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值