zoukankan      html  css  js  c++  java
  • PTA (Advanced Level)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 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
    
    思路
    • 将数字转换为字符串,每隔3个输出一个,,要注意的点写在代码注释里了
    代码
    #include<bits/stdc++.h>
    using namespace std;
    
    int main()
    {
    	int a,b;
    	cin >> a >> b;
    	int ans = a + b;
    	if(ans / 1000 == 0)		//只有3位
    		cout << ans;
    	else
    	{
    		vector<char> v;
    		int cnt = 0;
    		int t;
    		char tmp;
    		if(ans < 0)
             {
            	cout << '-';
            	ans = -ans;
             }
    		while(ans)
    		{
    			t = ans % 10;
                 tmp = t + '0';
    			v.push_back(tmp);
    			ans /= 10;
    			cnt++;
    			if(cnt == 3 && ans)		//为了避免输出形如-,999,991这样的答案
    			{
    				v.push_back(',');
    				cnt = 0;
    			}
    		}
    		for(int i=v.size()-1;i>=0;i--)
    			cout << v[i];
    	}
    	return 0;
    }
    
    
    
    引用

    https://pintia.cn/problem-sets/994805342720868352/problems/994805528788582400

  • 相关阅读:
    Kafka集群搭建
    Easyui dialog中嵌入iframe
    图表插件Charts.js的使用
    抽象工厂
    工厂方法
    简单工厂模式
    认识Git
    代理模式
    原型设计Axure的基本使用
    MVC Api 的跨项目路由
  • 原文地址:https://www.cnblogs.com/MartinLwx/p/11706810.html
Copyright © 2011-2022 走看看