问题
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