欧拉计画#13

时间:2019-02-28 09:36:57

标签: c

Project euler problem 13

对于C程序,我通过实用的方法尝试了该问题,即未在代码中定义数据,而是使用scanf进行输入。

但是我不明白为什么输出错误!我得到1373762303,而应该是5537376230。 2-3个数字似乎还可以。

@Override
public void onNewToken(String token) {
Log.d(TAG, "Refreshed token: " + token);

// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// Instance ID token to your app server.
sendRegistrationToServer(token);
}

2 个答案:

答案 0 :(得分:0)

scanf用从输入构成的字符串(包括空终止符字节)填充数组。您正确分配了51个字节,但是当您开始添加数字时,您从索引50(即nul字节的索引)开始。实际数字在0到49之间。

这意味着您将在某个时候将进位带入答案的单位数字,因为该数字的答案计算为

answer[50] += (str[i][50] - 48) + carry;
//                        ^^^^ correction applied for ASCII

另一个问题是,在添加每个新数字时,您忘记将进位重置为零。

这可能有效(未经测试),但仍然不能真正处理高位溢出

for(int i = 0; i < STRINGS; i++){
    scanf("%s", str[i]);
    carry = 0;            // Reset the carry
    for(int j = NUM - 1; j >=0; j--){
        answer[j] += (str[i][j] - 48) + carry;
        if(answer[j] > 9){
            carry = answer[j] / 10;
            answer[j] %= 10;
        }else{
            carry = 0;
        }
    }
}

答案 1 :(得分:0)

我得到了答案,这是两个数字相加时丢失的遗留物。解决方法如下:

#include <stdio.h>
#include <ctype.h>
#include <strings.h>
#define NUM 50
#define STRINGS 100
#define OUTPUT 10
int main(void) {
    char str[STRINGS][NUM+1];
    int answer[NUM+1] = {0};
    int carry = 0, out_digits = OUTPUT, intm_carry = 0;

    for(int i = 0; i < STRINGS; i++){
        scanf("%s", str[i]);
        for(int j = NUM; j >=0; j--){
            answer[j] += (str[i][j] - 48) + carry;
            if(answer[j] > 9){
                carry = answer[j] / 10;
                answer[j] %= 10;
            }else{
                carry = 0;
            }
        }
        intm_carry += carry;
        carry = 0;
    }
    printf("--------------------------------------------------\r\n");
    printf("%d", intm_carry);
    for(int j = 0; j < OUTPUT-1; j++){
        printf("%d",answer[j]);
    }
    printf("\r\n--------------------------------------------------");
    return 0;
}
相关问题