题目描述: 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
constint max_int = (1 << 31) - 1; constint min_int = -max_int - 1; classSolution { public: intreverse(int x){ int y = 0; int n; while(x != 0) { n = x % 10; if(y > max_int / 10 || y < min_int / 10) return0; y = y * 10 + n; x /= 10; } return y; } };
#!/usr/bin/env python3 defreverse(x): s = str(x) if(x >= 0): res = int(str(x)[::-1]) else: res = -int(str(-x)[::-1]) if res > 2 ** 31 - 1or res < -2 ** 31: return0 return res if __name__ == '__main__': a = reverse(-10324) print(str(a))
String to Integer (atoi)
题目描述:
Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
题目描述: Determine whether an integer is a palindrome. Do this without extra space. 思路:注意到负数不是回文数。给一个数32623,首先计算出这个数的长度,即算出它的数量级,最高位是千、万还是十万位,然后逐步分离该数字的最低位和最高位,拿最低位和最高位进行比较,如果不相等就不是回文数,否则即为回文数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public: boolisPalindrome(int x){ if(x < 0) returnfalse; int len = 1; int lhs = 0; int rhs = 0; for(int temp = x / 10; temp != 0; temp /= 10, len *= 10); while(x) { lhs = x / len; rhs = x % 10; if(lhs != rhs) returnfalse; x = (x % len) / 10; len /= 100; } returntrue; } };