题目:
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?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
我是这样写的:
1 class Solution { 2 public: 3 int reverse(int x) { 4 // int temp = INT_MAX; 5 int count = 0; 6 int y = x; 7 while(abs(y) > 0) 8 { 9 y = y/10; 10 count++; 11 } 12 if(x == 0) 13 return 0; 14 else if(x > 0) 15 { 16 int *a = new int[count]; 17 for(int i = 0; i < count; i++) 18 { 19 a[i] = x%10; 20 x = x/10; 21 } 22 int value = 0; 23 int temp = 0; 24 for(int j = 0; j < count; j++) 25 { 26 value = value*10 + a[j]; 27 if(temp != (value - a[j])/10) value = temp = 0; 28 else temp = value; 29 } 30 delete []a; 31 return value; 32 } 33 else 34 { 35 x = -x; 36 int *a = new int[count]; 37 for(int i = 0; i < count; i++) 38 { 39 a[i] = x%10; 40 x = x/10; 41 } 42 int value = 0; 43 int temp = 0; 44 for(int j = 0; j < count; j++) 45 { 46 value = value*10 + a[j]; 47 if(temp != (value - a[j])/10) value = temp = 0; 48 else temp = value; 49 } 50 delete []a; 51 return -value; 52 53 } 54 55 } 56 };
通过之后,我参考了网友doc_sgl的代码
http://blog.csdn.net/doc_sgl/article/details/12190507
他是这样写的:
1 int reverse(int x) { 2 // Start typing your C/C++ solution below 3 // DO NOT write int main() function 4 5 long res = 0; 6 while(x) 7 { 8 res = res*10 + x%10; 9 x /= 10; 10 } 11 return res; 12 }
十几行与几十行的区别,却能更简便的表述。虽然这些代码没有仔细思量裁剪,但却表现了代码能力的区别。以此自省之。
时间: 2024-10-09 07:33:22