leecode第一次打卡

1、整数反转

leecode第一次打卡_第1张图片

class Solution(object):
    def reverse(self, x):
        y = abs(x)
        s = str(y)
        length = len(s)
        w = 0
        for i in range(length):
            var1 = y%10
            w += var1 * pow(10,length - 1 - i)
            y = y//10
        if w>pow(2,31):
            return 0
        if x>=0:
            return w
        elif x<0:
            return -w

思路:1、将输入的数转为绝对值,再转为字符串,得到字符串的长度

2、从低位向高位逐个得到数字,乘10的length-i次方将低位数转换为高位数

3、绝对值大于2的31次方时,返回0;输入的数大于0时,返回绝对值,小于0时,返回绝对值的相反数。

2、宝石与石头

leecode第一次打卡_第2张图片

class Solution(object):
    def numJewelsInStones(self, jewels, stones):
        l1 = len(jewels)
        l2 = len(stones)
        sum = 0
        for i in range(l1):
            for j in range(l2):
                if jewels[i] == stones[j]:
                    sum += 1
        return sum

思路:逐个字母遍历jewel和stones字符串列表,若字符相同,sum就加一。

3、数组串联

leecode第一次打卡_第3张图片

class Solution(object):
    def getConcatenation(self, nums):
        a = []
        length = len(nums)
        for i in range(0,2*length,length):
            for j in range(length):
                a.append(nums[j]) 
        return a

思路:1、以数组的长度为步长,新数组要串联的次数×数组的长度为总长度进行遍历,大循环控制串联次数

2、小循环遍历nums数组将元素添加到新数组中

 

 

你可能感兴趣的:(leetcode,算法,职场和发展)