【PAT甲级】1001 A+B Format

时间:2020-01-22 20:03:45   收藏:0   阅读:72

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 ?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



思路



代码

#include<iostream>
#include<string>
#include<math.h>

using namespace std;

int main() {

    int a;
    int b;
    cin>>a;
    cin>>b;

    int c=a+b;
    string cString=to_string(c);//int转string
    string resultStr="";//输出结果字符串

    int count=0;//已遍历数字的个数
//插逗号时,从后往前 遍历数字;一边遍历一边赋值给另一个字符串
    int i;//下标
    if(c==0)
        i=0;
    else if(c<0) //c为负数,加一个符号位
        i=(1+(int)log10(abs(c)))+1-1;
    else
        i=(1+(int)log10(abs(c)))-1;
        
    for(; i>=0; i--) {
        string insertStr(1,cString.at(i));//char转为string

        resultStr.insert(0,insertStr);
        count++;
        if(count%3==0) {
            if(i==0||cString.at(i-1)=='-') { //不能插逗号:i指向元素是第一位数字;i指向元素前面一位为负号
            } else {
                resultStr.insert(0,",");
            }
        }
    }

    cout<<resultStr;
    return 0;
}



知识点



BUG

技术分享图片

1+(int)log10(abs(c))不能计算c=0的情况,需要另外处理


解决:

    if(c==0)
        i=0;
    else if(c<0) //c为负数,加一个符号位
        i=(1+(int)log10(abs(c)))+1-1;
    else
        i=(1+(int)log10(abs(c)))-1;


注意

  1. 当已遍历数字个数是3的倍数,但不能插逗号的情况:

    当前遍历的数字已经是数字串的首个数字:

    • 数字串是正数:当前遍历的数字是第一位(i==0)

    • 数字串是负数:前一位是符号‘ - ’

        if(count%3==0) {
            if(i==0||cString.at(i-1)=='-') { //不能插逗号:i指向元素是第一位数字;i指向元素前面一位为负号
            } else {
                resultStr.insert(0,",");
            }
        }



单词

comma:逗号

原文:https://www.cnblogs.com/musecho/p/12229427.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!