在C中反转多位数。

时间:2021-07-21 19:53:13

I have problem, where-in I need to take maximum of 10000 test cases as inputs and have 5000 maximum digits and have to reverse the digits.

我有一个问题,我需要把10000个测试用例的最大值作为输入,并且有5000个最大的数字,并且必须将数字颠倒过来。

If suppose I only give 3 testcases and a random no of digits per testcase as below,

如果假设我只给出了3个testcase和一个随机数字,每个testcase的数字如下,

n = 3,

n = 3,

1] 12 43 => these are the digits => o/P 55
2] 90 235 => o/P is 09 + 532 = 541
3] 23 98899 3454 2323 => o/P is 32 + 99889 + 4543 + 3232 = 107696  

I need to take these digits as input. Can I take these in an integer array. After storing the digits, I have to reverse the digits and add them. 1] 12 43 can be reversed as 21 34 and added as 21 + 34 = 55. The output is 55

我需要把这些数字作为输入。我可以把它们放在整数数组中吗?在存储数字之后,我必须将数字倒过来并添加它们。1]1243可以反过来为21 34,加21 + 34 = 55。输出是55

We can reverse a single digit with the below formula,

我们可以用下面的公式来改变一个数字,

num = 12345
rev_num = 0
while(num > 0) {
  rev_num = (rev_num * 10) + (num%10)
  num = num/10
}

But dunno the correct data structure to store it inorder to reverse the multiple digits inputted on a single line and to add the reversed data. int n; int (*p)[n]; Cant we have a dynamic declaration of arrays according to the value of n. How to solve this problem.

但是,dunno正确的数据结构可以存储它,以反转单个行中输入的多个数字,并添加反向数据。int n;int(* p)[n];根据n的值,我们不能有一个动态的数组声明,如何解决这个问题。

2 个解决方案

#1


3  

  1. Use fgets() to read the input.
  2. 使用fgets()读取输入。
  3. Break the input to strings using strtok() with space as delimiter.
  4. 使用strtok()以空格作为分隔符将输入拆分为字符串。
  5. Reverse the string using strrev() for each token.
  6. 使用strrev()为每个令牌反转字符串。
  7. Then use atoi() to convert the tokens to integers.
  8. 然后使用atoi()将令牌转换为整数。
  9. Once you have the integers perform addition.
  10. 一旦你有了整数,执行加法。

#2


0  

You can convert the number (integer) to string then reverse the string and convert back to integer. To reverse the string, you can use the strrev() function. Note that strrev() is not a standard function and it may not available in standard C library

您可以将数字(整数)转换为字符串,然后将字符串转换为整数。要反转字符串,可以使用strrev()函数。注意,strrev()不是标准函数,它可能无法在标准C库中使用。

#1


3  

  1. Use fgets() to read the input.
  2. 使用fgets()读取输入。
  3. Break the input to strings using strtok() with space as delimiter.
  4. 使用strtok()以空格作为分隔符将输入拆分为字符串。
  5. Reverse the string using strrev() for each token.
  6. 使用strrev()为每个令牌反转字符串。
  7. Then use atoi() to convert the tokens to integers.
  8. 然后使用atoi()将令牌转换为整数。
  9. Once you have the integers perform addition.
  10. 一旦你有了整数,执行加法。

#2


0  

You can convert the number (integer) to string then reverse the string and convert back to integer. To reverse the string, you can use the strrev() function. Note that strrev() is not a standard function and it may not available in standard C library

您可以将数字(整数)转换为字符串,然后将字符串转换为整数。要反转字符串,可以使用strrev()函数。注意,strrev()不是标准函数,它可能无法在标准C库中使用。