C程序将数字反转
我正在寻找用于反转数字的 C
程序,如下所示:
如果我输入:
123456
那么结果将是:
654321
请帮助我。
I am looking for the C
program for reverse the digits like below:
If i enter:
123456
Then the result would be:
654321
Please help me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
这是这个复杂问题的简单解决方案:
A new version that outputs the newline:
Here is a simple solution to this complex problem:
A new version that outputs the newline:
如果您的教授正在对您的表现进行评分,请尝试 ggf31416 在另一个问题中对此问题的解决方案:
优化®
绝对必须在纳秒内完成。
If your professor is grading you on performance, then try ggf31416's solution to this problem in another question:
Optimization®
When it absolutely, positively has to be done this nanosecond.
使用
%10
获取最后一位数字。输出它。将数字除以 10 即可得到除最后一位数字之外的所有数字。使用% 10
获取最后一位数字。以此类推,直到数字变为0。Use
% 10
to get the last digit. Output it. Divide the number by 10 to get all but the last digit. Use% 10
to get the last digit of that. And so on, until the number becomes 0.这是另一种可能性。它是非递归的,并且代码可能会少一些。代码注释中有一个例子来解释逻辑。
Here is another possibility. It is non-recursive, and perhaps a little less code. There is an example in the code comments to explain the logic.
使用
scanf("%s", A)
读取字符数组A
中的数字,或者更好的是使用fgets
并通过输出从strlen(A) 开始的每个字符来反转 char 数组 - 1
到0
。Read the number in a char array
A
withscanf("%s", A)
or, better, withfgets
and output the char array reversed by outputting each character starting fromstrlen(A) - 1
to0
.strrev 函数反转字符串。如果性能不是问题,那么例如您可以先执行 itoa,然后执行 strrev,然后执行 atoi。
但即使没有strrev,任务也很简单。
strrev function reverses the string. If performance is not a problem then for instance you can do itoa, then strrev, then atoi.
But the task is very simple even without strrev.
看起来像一个非常古老的线程。但我在这里引用了这些解决方案,并且在测试了该网站上可用作解决方案的不同程序后,必须制定自己的解决方案。我意识到,如果数字以零结尾,则将数字视为 int 不会产生必要的数字反转。所以我决定将数字视为字符串,然后将数字反转。这样,我从字符串的角度得到了数字的精确反转,而不是在数字开头丢弃零的数学数字。
Looks like a very old thread. But I referred the solutions here and had to cook up my own solution after testing the different programs available as solution on this website. I realized that treating the number as int will not yield necessary reversing of digit if the number ends with zero(s). So I decided to treat the number as a string and then reverse the digits. This way, I get exact reverse of the digit from a string standpoint and not a mathematical one that discards zeros at the beginning of a number.
使用幂函数。
use the power function.