c语言字符串逆序1001无标题,PAT真题(C语言)——1001:A+B Format

博主决定参加十二月的PAT考试,虽然代码水平还在入门阶段,但希望通过记录刷题过程提升自己。本文分享了第一题的解题思路,题目要求计算两个数的和,并按特定格式输出。博主采用了从低位到高位处理数字的方法,将结果存入数组,然后逆序输出并插入逗号。代码时间复杂度为O(n)。
摘要由CSDN通过智能技术生成

今天已经是九月26日了,突然心血来潮想去考十二月的PAT,但目前的代码水平还刚到幼儿园水平,就用这个博客记录一下刷题的心得吧。

今天是第一题。题目如下:

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 −10^6 ​​ ≤ a, b ≤ 10 ^​6 ​​ .

The numbers are separated by a space.

Output Specification: For each test case, you should output the sum ofa and b in one line. The sum must be written in the standard format.

Sample Input:

-1000000^9

Sample Output:

-999,991

思路:这道题属于基础题,难度不高,但可以考虑怎么用更加高效的方法实现,目前想到的是很基础的方法,即将两数相加以后,将结果的每一位分步存进一个数组中,在按原本的顺序打印出来,并在合适的位置加上逗号以及正负号。

这道题目首先一个问题就是,判断的过程肯定得是从低位开始,这是因为我们不知道这个数究竟有几位,当然也可以用一个循环先判断结果的位数,我这里采用的是从低位到高位进行判断,从低到高将数存进数组,需要注意的是,数组里的数的顺序和将要输出的顺序是相反的,因此需要从后往前打印,代码如下:

#include

int abs(int i){

if(i<0)

i = -i;

return i;

}

int main(){

int a, b;

int c;

int temp[10];

int i;

int j = 1;

scanf("%d", &a);

scanf("%d", &b);

/*if(b1000000 || a1000000)

return -1;*/

c = a + b;

for(i=0; i<10;i++){

if(j%4 == 0)

temp[i] = 10;

else{

temp[i] = c % 10;

c /= 10;

}

j++;

if(c == 0)

break;

}

if(a+b < 0){

printf("-");

}

for(; i>=0;i--){

if(temp[i] == 10)

printf(",");

else

printf("%d", abs(temp[i]));

}

return 0;

}

至于逗号,我是用的是在需要加逗号的地方,给最终的数组赋值为10,输出的时候,遇到10就打印逗号就行。整个程序时间复杂度为0(n)。

如果遇到更加优秀的方法,学会了再来此贴更新。

嗯!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值