zoukankan      html  css  js  c++  java
  • PAT 1001 A+B Format

    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

    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.

    Output

    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



    题目意思:A+B求和,然后每三位为一个单位加上一个“,”的格式输出。
    解题思路:转换成字符串来遍历会很方便,注意若是负数第一位负号也要占位的,并且要求最后一位不能出现“,”,其实可以看看遍历到当前位时剩下的位数若是3的倍数,那么就需要加“,”了。

    #include<iostream>
    #include<algorithm>
    #include<string>
    using namespace std;
    int main()
    {
        int a,b,len;
        int i;
        string str;
        cin>>a>>b;
        str=to_string(a+b);
        len=str.size();
        for(i=0;i<len;i++)
        {
            cout<<str[i];
            if(str[i]=='-')
            {
                continue;
            }
            if((len-i-1)%3==0&&i!=len-1)
            {
                cout<<",";
            }
        }
        return 0;
    }
    
    

    注意这里的to_string是C++11里面string中所包含的函数。


  • 相关阅读:
    简单图表分析(2/2)
    简单图表分析(1/2)
    juqery dragsort使用遇到的问题
    移动端实战总结
    CSS VS JS动画,哪个更快[译]
    HTML5移动端图片上传模块
    移动端使用rem适配及相关问题
    再谈vertical-align与line-height
    Javascript中的Promise
    Retina屏实现1px边框
  • 原文地址:https://www.cnblogs.com/wkfvawl/p/11017042.html
Copyright © 2011-2022 走看看