美文网首页
2018-04-22 pat1017

2018-04-22 pat1017

作者: 六月初断后中 | 来源:发表于2018-04-22 16:53 被阅读0次

本题要求计算A/B,其中A是不超过1000位的正整数,B是1位正整数。你需要输出商数Q和余数R,使得A = B * Q + R成立。

输入格式:

输入在1行中依次给出A和B,中间以1空格分隔。

输出格式:

在1行中依次输出Q和R,中间以1空格分隔。

输入样例:
123456789050987654321 7
输出样例:
17636684150141093474 3
马菲菲 马飞飞 马飞飞

经验教训

  1. 其实本质是一个手算除法,但我把它想复杂了,第一个数字太大,可以用字符数组储存,这没错,但是我浪费了内存空间,将每一个数字字符转换成整数,再申请一块整数列表用来存储。其实根本没有必要,只需要计算时用字符减去‘0’就行了,简而言之,浪费空间。
  2. 最后一步的特殊边界检查不充分,如果被除数只有1位,且使得商为0,那么就不能再把0忽略。
#include <stdio.h>
int main()
{
    int i;
    int B;
    char A[1001], *p = A;
    
    scanf("%s %d", A, &B);
    
    /* read 2 digits from highest digit of A, do manual division, get the quotient
     and remainder. Read one more digit, combine this with the last remainder to
    get a new 2-digits number. Do this until read to the end of A */
    /* the results are stored in A and B instead of printed out on-the-fly */
    int twodigit, remainder = 0;
    for(i = 0; A[i]; i ++)
    {
        twodigit = remainder * 10 + (A[i] - '0');
        A[i] = twodigit / B + '0';
        remainder = twodigit % B;
    }
    B = remainder;
    
    /* print */
    if(A[0] == '0' && A[1] != '\0') p++;
    printf("%s %d", p, B);
    
    return 0;
}

相关文章

网友评论

      本文标题:2018-04-22 pat1017

      本文链接:https://www.haomeiwen.com/subject/ussclftx.html