input : a output : b int b = 0; int max = INT_MAX / 10; while (a > 0){ int a1 = a % 10; if (b > (INT_MAX-a1) / 10) error overflow; b = b * 10 + a1; a = a / 10; }
【在 g*********s 的大作中提到】 : reverse the string, then compare with the string of INT_MAX lexically? : need both itoa() and atoi().
J*a
6 楼
另外这个solution显然不好,如果题目变成把两个6进制整数倒过来怎么办?
【在 g*********s 的大作中提到】 : reverse the string, then compare with the string of INT_MAX lexically? : need both itoa() and atoi().
g*s
7 楼
i didn't check the details but this one looks better.
【在 J********a 的大作中提到】 : input : a : output : b : int b = 0; : int max = INT_MAX / 10; : while (a > 0){ : int a1 = a % 10; : if (b > (INT_MAX-a1) / 10) error overflow; : b = b * 10 + a1; : a = a / 10; : }
to detect the overflow, you can take the last digit off the orginal number b efore reverse, with one less digit, the modified number should not be overfl ow then after reversing, you patch the last digit to the reversed number given you know the number of digits already, from now on, you have several ways to detect overflow, depending on whether the number is signed or unsigned