(查看最终代码请直接看最后一个代码段)
还有两周考pat,好久没写c++代码了,极限刷题一波,看看有没有机会抱佛大腿。
题目
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
结尾无空行
思路
先算出两数之和作为待处理数,然后除以1000取余数,将取到的余数压入栈内(这里我嫌麻烦没有定义专门的栈结构,而是直接在普通数组上操作),再将除法的商作为新的待处理数。待全部入栈后再从栈顶依次取出加上“,”。
注意事项(我想到的):
- 要注意栈大小,这里限制了a,b小于等于10的6次方,意味着结果最大为2乘以10的6次方,即最多分3节,代表栈的数组长度就可以取3。
- 给出的输出标准中最后不是逗号。
我的通过代码:
#include <iostream>
using namespace std;
int main(){
int a,b,s,result[3]={-1,-1,-1};
cin>>a;
cin>>b;
s=a+b;
int i=0;
if(s<0){
cout << "-";
s=s*(-1);
}
while(s>=1000){
result[i++]=s%1000;
s/=1000;
}
result[i]=s;
for(int j=i;j>=0;j--){
if(result[j]>=100 || j==i){
cout<<result[j];
}
else if(result[j]>10){
cout<<0;
cout<<result[j];
}
else{
cout<<0;
cout<<0;
cout<<result[j];
}
if(j==0){
break;
}
cout << ",";
}
return 0;
}
做题过程中我遇到的问题:
- 忘了处理符号,导致负数打印出来每节数字前面都带负号 ╮(─▽─)╭
- 没考虑到会出现每一节开头的0会被丢弃(例如1001打印成1,1)。
更多:
搜索发现两点:
- 用c中的printf("%0md",p)方法可以直接确保输出的数字一定是m位,不足的自动在高位补0,这样就不用自己判断需要补几个0了。注意:
- 使用scanf和printf需要#include <stdio.h>库
- 《算法笔记》上建议不要同时用两种输入输出方法
- c++中有stack类,这样就不用花心思考虑数组范围和每次调用的下标。用法:
- #include <stack>
- 定义:stack <elemtype> stackname
- stackname.empty() 栈为空则返回真
- stackname.push(elem)
- stackname.top() 返回栈顶元素
- stackname.pop() 删除栈顶元素,请注意这里只删除,返回的是void,请按需在此之前调top()
- stackname.size() 返回栈中元素数目
修改后通过的代码如下:
#include <stack>
#include <stdio.h>
using namespace std;
int main(){
int a,b,s,p,size0,size;
stack <int> result;
scanf("%d%d",&a,&b);
s=a+b;
if(s<0){
printf("-");
s=s*(-1);
}
while(s>=1000){
result.push(s%1000);
s/=1000;
}
result.push(s);
size0=result.size();
while(true){
p=result.top();
size=result.size();
result.pop();
if(p>=100 || size==size0){
printf("%d",p);
}
else{
printf("%03d",p);
}
if(result.empty()) break;
printf(",");
}
return 0;
}
遇到的坑:
- pop()返回空。
- 在判断第一节时(为了避免在头部加0),一开始想到的方法是:在循环外取栈顶元素赋给变量top,然后循环内判断top()方法取到的值和top是否相等。忽略了可能不止一次出现和top一样的元素(例1001001)。呜呜,后来通过栈长度size来判断就没问题了。