Reverse number function in C

给你一囗甜甜゛ 提交于 2019-12-11 08:17:57

问题


So if I input say 092, it does not return 290, instead returns 29 which is not what I want it to do. Any advice?

int reverseNumber(int number){
    int ans = 0;
    while(number > 0) {
        int rightDigit;
        rightDigit = number % 10;
        ans =ans *10 + rightDigit;
        number = number / 10;
    }
    return ans; 
}

回答1:


It is because 029 is no different from 29 decimal1. For this to work you need to take the input as a string instead, and invert the characters. After that you can convert the resulting string to a number.


1A leading 0 means it's an octal number, but in this particular case it has a 9 which is not an octal digit. Depending on how you convert from numbers to strings, this can be something to consider. But if you are just scanf()ing it, then it will be decimal for sure.




回答2:


You can't have 092 in int.

cin>>a;  //a=092
cout<<a; //it will print 92

So, you should take input as string and then you could reverse the string.



来源:https://stackoverflow.com/questions/41797642/reverse-number-function-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!