Problem C
If We Were a Child Again
Input: standard input
Output: standard output
Time Limit: 7 seconds
“Oooooooooooooooh! If I could do the easy mathematics like my school days!! I can guarantee, that I’d not make any mistake this time!!” Says a smart university student!! But his teacher even smarter – “Ok! I’d assign you such projects in your software lab. Don’t be so sad.” “Really!!” - the students feels happy. And he feels so happy that he cannot see the smile in his teacher’s face.
| ![]() | |
The Problem
The first project for the poor student was to make a calculator that can just perform the basic arithmetic operations.
But like many other university students he doesn’t like to do any project by himself. He just wants to collect programs from here and there. As you are a friend of him, he asks you to write the program. But, you are also intelligent enough to tackle this kind of people. You agreed to write only the (integer) division and mod (% in C/C++) operations for him. | ||
Input Input is a sequence of lines. Each line will contain an input number. One or more spaces. A sign (division or mod). Again spaces. And another input number. Both the input numbers are non-negative integer. The first one may be arbitrarily long. The second number n will be in the range (0 < n < 231). | ||
OutputA line for each input, each containing an integer. See the sample input and output. Output should not contain any extra space. | ||
Sample Input110 / 100 99 % 10 2147483647 / 2147483647 2147483646 % 2147483647 |
| |
Sample Output1 9 1 2147483646 |
|
2217除以21,一开始,我的计算方式是想找个数,比如21是两位数,那么就从第二位开始算22/21=1......1;1*10+1=11 11/21=0......11 (11*10+7)/21=5 所以最后的结果就是把数组输出105;
大概思路就是从第几位开始除,然后把除的结果用数组记下来,然后取余×10加下一位,最后把数组输出
但是,有个问题大家注意没有
这里是22÷21,如果是20除以21呢,不会出来前导0吗?还有,如果后面的数比前面的大怎么办?(我的错误)
这两个问题不解决,程序是不会AC的
为此,我想出了一个解决方案,
第一,反正可能出现0那么,就不从那个被除数的位数开始了,直接从第一位开始;
第二,后面比前面的数大就是输出0的问题,那就是前导0呗,你看前导0也不是没用;
第三,前导0也只有后面比前面数大的时候才会输出,这样条件是不是太麻烦了?其实不然,你看看代码,就懂了
#include<stdio.h>
#include<string.h>
#define max 10000
char a[max];
long b[max];
int main()
{
char c;
long n;
while(scanf("%s %c %ld)",a,&c,&n)!=EOF)
{
memset(b,0,sizeof(b));/*这个如果忘了,可能会出错哦*/
if(c=='/')
{
long i,m,k=0,j,p;
for(j=0,m=0; m<strlen(a); m++,j++)
{
k=k*10+a[m]-'0';
b[j]=k/n;
k=k%n;
}
p=0;
while(b[p]==0&&p<j-1)/*到核心了,别看这句话不长但是代表的意思可不少,你想想是不是如果最后一*/
p++; /*个数也是0那么就代表着,那个条件成立了?*/
for(i=p; i<j; i++)
printf("%ld",b[i]);
printf("\n");
}
else
{
long j,k=0;
for(j=0; j<strlen(a); j++)
{
k=k*10+a[j]-'0';
k=k%n;
}
printf("%ld\n",k);
}
}
}
注意,不要用int交,可能会错的