加密一组整数

时间:2014-12-05 11:34:14

标签: c

我有一个问题场景,在哪里,我必须

  

1]得到n个测试用例2]得到数字的输入[可以   单行中的多个整数]例如:12 34 123 3]将no的反转为   21 43 321 4]再次添加反转的数字21 + 43 + 321 = 365 5]   将no 365反转为563 6]输出为563

     

以上是1个此类测试用例的示例。如果testcase = 3 Input1 => 21   22 100:O / P => 12 + 22 + 001 = 35 => final op => 53输入2 => 11   100 32:O / P => 11 + 001 + 23 = 35 => final op => 53输入3 => 100   21:O / P => 001 + 12 = 13 => final op => 31

#include<stdio.h>
#include<string.h>
#include<malloc.h>

#define MAX_N 10000
#define MAX_D 5000

int reverse_digits(char* temp){
        int no,rev_no = 0;
        if(temp == NULL) return -1;
        no = atoi(temp);
        printf("\n no : %d \n",no);
        while(no > 0){
                rev_no = ((rev_no * 10)+(no % 10));
                no = no/10;
        }
        return rev_no;

}
int main(){
        int number,prev_no,sum,i;
        char* temp1 = NULL;
        char* test_case = malloc(10);
        char* n = malloc(MAX_D);
        char* op = malloc(MAX_D);
        if(NULL == n || NULL == test_case || NULL == op) return -1;
        number = prev_no = sum = i = 0;
        fgets(test_case,10,stdin);
        for(i = 0; i < atoi(test_case); i++){
                memset(op,0,MAX_D);
                fgets(n,MAX_D,stdin);
                temp1 = strtok(n," ");
                prev_no = reverse_digits(temp1);
                printf("\n prev_no : %d \n",prev_no);
                while(temp1 != NULL){
                        temp1 = strtok(NULL, " ");
                        if(temp1 != NULL){
                                number = reverse_digits(temp1);
                        }
                        sum = prev_no + number;
                        prev_no = sum;
                }
                printf("\n sum : %d \n",sum);
                sprintf(op,"%d",sum);
                printf("\n op : %s` \n",op);
                printf("\n rev: %d \n",reverse_digits(op));
        }
        return 0;
}

如果我将输入作为1和一个整数给出如下,我得到垃圾值的答案。无法得到原因。

OP:

angus@ubuntu:~/angus/myschool$ ./a.out 
1
12

 no : 12 

 prev_no : 21 

 sum : 21 

 op : 21` 

 no : 21 

 rev: 3254512 
答案必须是12。

1 个答案:

答案 0 :(得分:1)

您忘记在rev_no初始化reverse digits

int reverse_digits(char* temp){
        int no,rev_no = 0;