简体   繁体   English

C ++中的数字反转

[英]Number Reversal in c++

When I pass an odd digit number > 1 to the function, I am getting 1 less than the actual result I should be getting and the code is working perfectly fine for an even digit number, I am not able to figure out why. 当我向该函数传递一个大于1的奇数数字时,我得到的比实际结果要少1,并且代码对于偶数数字来说运行得很好,我无法弄清楚为什么。

int rev_number(int num){
int arr [10];
int i=0;
int j=0;
int rev_num=0;
while(num > 0){
    arr[i] = num%10;
    num = num/10;
    i++;
}
i--;
while(i>=0){
    rev_num += arr[j] * pow(10,i);
        j++;
        i--;
    }
    return rev_num;
}

You should avoid using pow which return a double while you only want to manipulate integers. 您应该避免使用pow它会返回一个double ,而你只想要操作的整数。 For example, imagine if the result of arr[j] * pow(10,i) is 753.99..., the cast would only put 753 in rev_num ! 例如,假设arr[j] * pow(10,i)为753.99 ...,则强制转换只会将753放入rev_num In some cases, that will work, but not always. 在某些情况下,这将起作用,但并非总是如此。 It's a fifty-fifty chance to work. 这是工作的机会五十。

Try replacing: 尝试更换:

rev_num += arr[j] * pow(10,i);

to

rev_num = rev_num * 10 + arr[j];

Have you tried to round or to add .5? 您是否尝试过四舍五入或添加.5? Does that also fix your problem? 这样还能解决您的问题吗?

How about the following simple code 下面的简单代码怎么样

int reverseNumber(int num) {
     int reverse = 0;
     while(num > 0) {
          reverse = reverse*10 + num%10;
          num = num/10;
     }
return reverse;
}

Since pow deals with floating point values, it's integer representation may get truncated, so certain values may end up being lower than expected. 由于pow处理浮点值,因此它的整数表示可能会被截断,因此某些值最终可能会低于预期。

A better solution is to use integer math, such as this: 更好的解决方案是使用整数数学,例如:

while(i>=0){
rev_num *= 10;
rev_num += arr[j];
    j++;
    i--;
}

There are several other ways to express the same thing, and storing the values in an array isn't strictly necessary, you could just multiply the modulo value back in. 还有其他几种表达同一事物的方法,并且严格地讲,不必将值存储在数组中,您可以将模数值乘回。

However, my favourite "reverse a number" is to read it in as a string, and then use the standard reverse function. 但是,我最喜欢的“反转数字”是将其作为字符串读取,然后使用标准的反转功能。

So, something like this: 因此,如下所示:

#include <string>
#include <algorithm>
#include <iostream>

int main()
{
   std::string s;
   std::cin >> s;
   std::reverse(s.begin(), s.end());
   std::cout << s << std::endl;
}

All code examples of the function showed here are invalid because the function does not process valid integer 0. So I decided to show a correct function realization.:) 这里显示的函数的所有代码示例均无效,因为该函数未处理有效的整数0。因此,我决定显示一个正确的函数实现。:)

using System;

namespace ReverseNumberExercise
{
    class Program
    {
        static int ReverseNumber(int x)
        {
            int y = 0;

            do
            {
                long digit;
                x = ( int )Math.DivRem( x, 10L, out digit );
                y = y * 10 + ( int )digit;
            } while ( x != 0 );

            return (y);
        }

        static void Main()
        {
            while (true)
            {
                Console.Write("Enter an integral number: ");

                string input = Console.ReadLine();

                if (string.IsNullOrEmpty(input)) break;

                int x;

                if (!int.TryParse(input, out x))
                {
                    Console.WriteLine("Invalid number. Try again.");
                }

                Console.WriteLine("Reversed number is: {0}", ReverseNumber(x));

                Console.WriteLine();
            }

            Console.WriteLine("\nGood bye!");
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM