String to Integer 和 Palindrome Number

一下贴两题,第一题是考虑各种case和代码怎么写的简化

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.

View Code PYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
    # @return an integer
    def atoi(self, str):
        INT_MIN, INT_MAX = -2147483648, 2147483647
        base, sign = 0, 1
        i = 0
        while i < len(str) and str[i].isspace():
            i += 1
        if i < len(str) and (str[i] == '-' or str[i] == '+'):
            sign = 1 - 2 * (str[i] == '-')
            i += 1
        while i < len(str) and str[i].isdigit():
            if base >  INT_MAX / 10 or (base == INT_MAX / 10 and int(str[i])> 7):
                if sign == 1:
                    return INT_MAX
                else:
                    return INT_MIN
            base  = 10 * base + int(str[i])
            i += 1
        return base * sign

Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.这题的没有extra space一开始我理解的是一个变量都不要,后来发现想不出方法来,所以就改成O(1),网上搜了下,很多人号称自己答案符合要求,其实用了一个和输入长度相同的int,那和把int反向在比较就没啥空间上的差别了.我的方法只有一个个位数变量

View Code PYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
    # @return a boolean
    def isPalindrome(self, x):
    	def getorder(x):
    		order = 0
    		while x >= 10:
    			x = x / 10
    			order += 1
    		return order
    	if x < 0:
    		return False
    	if x < 10:
    		return True
    	order = getorder(x)
    	while x:
    		first = x / pow(10,order)
    		if x%10 != first:
    			return False
    		else:
    			x = (x - first * pow(10,order)) / 10
    			order -= 2
    	return True
Share This: 

Leave a Reply

Your email address will not be published. Required fields are marked *