首页 > 其他 > 详细

【PAT甲级】1001 A+B Format

时间:2020-01-22 20:03:45      阅读:69      评论:0      收藏:0      [点我收藏+]

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



思路

  • 不能直接从前往后遍历结果c的各位数字将其一个一个输出,因为考虑输出逗号需要从后往前计算数字个数。

  • 思路:

    设置一个存放最终输出结果的字符串。从后往前遍历各位数字,每次将其插在结果字符串的开头。同时计算已经遍历数字的个数,若个数是3的倍数,且当前遍历的数字不是第一位数字,则插入逗号。



代码

#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;
}



知识点

  • string::at()返回值为char&类型

  • string::insert(下标i,字符串) //字符串插在字符串的下标i后

  • 计算c的位数,c不能为0

    1+(int)log10(abs(c))
  • 数据类型转换

    • string::to_string(c)//int转string

    字符串是从第一个字符开始存的: (c=-999,991)cString.at(0)是-

    • string::insertStr(1,cString.at(i)) //char转为string



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:逗号

【PAT甲级】1001 A+B Format

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!