lintcode入门篇九

413. 反转整数

中文English

将一个整数中的数字进行颠倒,当颠倒后的整数溢出时,返回 0 (标记为 32 位整数)。

样例

样例 1:

输入:123
输出:321

样例 2:

输入:-123
输出:-321

class Solution:
    def reverseInteger(self,n):
        tag = True
        if n > 0:
            n = n
        else:
            tag = False
            n = abs(n)

        res = 0
        l = []
        while  n > 0:
            num = n%10
            n = n//10
            l.append(num)
    
        for i in range(len(l)):
            res = res + l[::-1][i]*10**i
        if tag == False:
            res = -res
        if -2**32+1 < res < 2**32-1:##注意,如果res在32位范围之内,则返回原数,否则返回0,[-255,255]
            return res
        return 0

417. 有效数字

中文English

给定一个字符串,验证其是否为数字。

样例

样例 1:

输入: "0"
输出: true
解释: "0" 可以被转换成 0

样例 2:

输入: "0.1"
输出: true
解释: "0.1" 可以被转换成 0.1

样例 3:

输入: "abc"
输出: false

样例 4:

输入: "1 a"
输出: false

样例 5:

输入: "2e10"
输出: true
解释: "2e10" 代表 20,000,000,000
输入测试数据 (每行一个参数)如何理解测试数据?
class Solution:
    """
    @param s: the string that represents a number
    @return: whether the string is a valid number
    """
    def isNumber(self, s):
        # write your code here
        try:
            float(s)
        except:
            return False
        return True

大致思路:

根据float(str)来进行判断,如果是浮点数或者是整数的话,float不会报错,返回true。如果是字符的话会报错,则返回false。

str.isalnum() 所有字符都是数字或者字母

str.isalpha() 所有字符都是字母

str.isdigit() 所有字符都是数字

str.isspace() 所有字符都是空白字符、t、n、r

原文地址:https://www.cnblogs.com/yunxintryyoubest/p/12461514.html