I*********e 发帖数: 61 | 1 Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if
you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such
as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is
a 32-bit integer, then the reverse of 1000000003 overflows. How should you
handle such cases?
Throw an exception? Good, but what if throwing an exception is not an option
? You would then have to re-design the function (ie, add an extra parameter).
遇到overflow时,能想到的是转换成string,但题目要求返回int。没想到怎么样“add
an extra
parameter”
请赐教。 | h****n 发帖数: 2094 | 2 Return value of the func is error code and another extra pointer for the
return integer value.
such
is
【在 I*********e 的大作中提到】 : Reverse Integer : Reverse digits of an integer. : Example1: x = 123, return 321 : Example2: x = -123, return -321 : Have you thought about this? : Here are some good questions to ask before coding. Bonus points for you if : you have already thought through this! : If the integer's last digit is 0, what should the output be? ie, cases such : as 10, 100. : Did you notice that the reversed integer might overflow? Assume the input is
| c*****a 发帖数: 808 | 3 我是按这解法做的
123 = 100 + 20 + 3
3=123%10
2= 123/10 %10
1 = 123/100%10
321 = 3* 100 + 2* 10 + 1 | t********e 发帖数: 344 | 4 int reverse(int num){
int rev = 0;
while(num != 0){
rev = num%10 + rev*10;
num = num/10;
}
return rev;
} |
|