gpt4 book ai didi

c - 加密一组整数

转载 作者:行者123 更新时间:2023-11-30 15:26:42 24 4
gpt4 key购买 nike

我有一个问题场景,我必须在其中

1] get n number of testcases 2] get the input of digits[Can be multiple ints in a single line] e.g: 12 34 123 3] reverse the no's as 21 43 321 4] add the reversed numbers 21 + 43 + 321 = 365 5] again reverse the no 365 to 563 6] the output is 563

Above is an example of 1 such test case. if testcase = 3 Input1 => 21 22 100 : O/P => 12 + 22 + 001 = 35 => final op => 53 Input2 => 11 100 32 : O/P => 11 + 001 + 23 = 35 => final op => 53 Input3 => 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 和一个整数,如下所示,我会得到带有垃圾值的答案。不明白为什么。

操作:

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

no : 12

prev_no : 21

sum : 21

op : 21`

no : 21

rev: 3254512

但是答案必须是 12。

最佳答案

您忘记在反向数字中初始化rev_no

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

关于c - 加密一组整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27315021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com