PAT(甲级)1001. A+B Format (20)

PAT 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).

输入格式:
Each input file contains one test case. Each case contains a pair of integers a and b where −10​^6 ≤ a , b ≤ 10​^6​​.The numbers are separated by a space.

输出格式:
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.

输入样例:

-1000000 9

输出样例:

-999,991

题目分析:按照指定的格式输出a+b的和,每三个数字一组,中间用逗号隔开,注意:不能输出前导0。

AC代码1(非递归):
算是一种投机的方法,题目中给出的数据范围是[10^-6, 10^6]意味着abs(sum(a+b))这个最大值是2*10^6=2 000 000,也就是说在这个题目中sum最多分三组。所以直接根据规律输出即可

//c/1000000 取得第一组的三位
//(c/1000)去掉低三位   (c/1000)%1000  获得去掉第三位中所得到的数字的低三位
//c%1000  获取c的低三位
//如1234567   分成三组为 1,234,567 
//c/1000000 得到1
//c/1000即为 1234   (c/1000)%1000即为234
//c%1000直接得到最低的三位

int main(){
	int a = 1234567;
	cout << "a = " << a << endl;
	cout << "a/1000000 = " << a/1000000 << endl;
	cout << "a/1000  = " << a/1000 << endl;
	cout << "(a/1000)%1000 = " << (a/1000)%1000 << endl;
	cout << "a%1000 = " << a%1000 << endl;
	return 0;
}

执行结果:
在这里插入图片描述

#include <cstdio>

int main(){
	int a, b, c;
	scanf("%d%d", &a, &b);
	c  = a+b;
	//统一将a+b的和处理为正数,方便逻辑的判断
	if(c < 0){
		printf("-");
		c = -c;
	}
	if(c>=1000000)//分三组
		printf("%d,%03d,%03d", c/1000000, (c/1000)%1000, c%1000);
	else if(c>=1000)//分两组	
		printf("%d,%03d", c/1000, c%1000);
	else//分一组
		printf("%d", c);
}

AC代码2(递归):

#include <cstdio>
void dfs(int n){
	//如果n<1000则说明位数小于等于3位  [0,999]直接输出即可
	//n<1000只有两种可能:(1)这个数字小于1000 (2)n是某个数字的高三位
	//注意不能输出前导0 如"032", 这样是错误的
	if(n < 1000){
		printf("%d", n);
		return;
	}
	else{
		//如果一个数字大于三位  [1000, infinite)
		//分成两个部分   高三位和其余位置
		//高三位 n/1000     最后三位 n%1000
		dfs(n / 1000);//输出高三位
		//所有的高三位都输出了,回溯回来  输出低三位即可
		printf("%3d", n % 1000);//注意此时的输出格式 "%03d", 不足三位需要用0补足
	}
}


int main(){
	int a, b, c;
	c = a+b;
	if(c<0){
		printf("-");
		c = -c;
	}
	dfs(c);
	return 0;
}
发布了235 篇原创文章 · 获赞 51 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/ASJBFJSB/article/details/90346163
今日推荐