LintCode中“新手必编程50题”答案
Python
作为看代码没问题却动手hin欠缺的程序媛&研究僧,又加之面临工作实习的笔试,就被迫在LIntCode上刷题了呗😂
科研其实更多的是读懂别人的代码,会根据自己的功能要求进行修改,所以本人在逻辑理解上还是不处于劣势滴~综上所述:反正我就是技术小菜😭
那就让我们做几个基础题练练手,再迎战难题吧(先保证运行再考虑效率),这些基础题的答案以备有人需要~~代码都是我亲测有效的~木有bug~若有问题,也欢迎大家提问,我好跟着学学😄。
之前没养成发布笔记的习惯,我决定!洗!心!革!面!重新做代码人~⛽️主要是“九章网站”的答案搜索麻烦还不完整> <
阶段1 基础数据类型
- 反转一个3位整数
注意精度,变量中使用int
class Solution:
"""
@param number: A 3-digit number.
@return: Reversed number.
"""
def reverseInteger(self, number):
# write your code here
a = number%10
b = (int(number/10))%10 #取出十位数
c = int(number/100)
return a*100 + b*10 + c
if __name__ == "__main__":
so = Solution()
print (so.reverseInteger(123))
⚠️注意这部分代码下面就不给出了,因为新版本的LintCode不需要这部分啦!
想用的小伙伴按照这个模版调用类中的定义函数即可~
if __name__ == "__main__":
so = Solution()
print (so.reverseInteger(123))
所以接下来我就只给出定义函数的代码~~~~
- 巴什博弈
⚠️既然是你先拿石头,n<=3你必赢;n=4你必输;n=5/6/7你必赢;n=8你必输…这是以4为周期在循环诶!
def canWinBash(self, n):
# Write your code here
a = n%4
if a == 0:
return False
else:
return True
- 计算圆周长和面积
⚠️先*100再/100,是为了保证计算精度
def calculate(self, r):
# write your code here
PI = 3.14
a = int(2*PI*r*100)
b = int(PI*r*r*100)
return a/100, b/100
- A+B问题
Python3中int 超过 0x7FFFFFFF 之后不会自动转成 long。
因此在 (a & b) << 1 时会就这么不断的往前进位,跳不出循环~
对应的思路是每次越界(超过 0x7FFFFFFF * 2 + 1, 所有 int 个数)就 and 一次。
最后再判断有没有最高位,有则为负数。
def aplusb(self, a, b):
# write your code here
INT_RANGE = 0xffffffff
while b!= 0:
a, b = (a^b), (a&b)<<1
a &= INT_RANGE
return a if a >> 31 <= 0 else a ^ ~INT_RANGE
阶段2 判断语句
- 简单计算器
⚠️python3的除法是//~~~~python2的除法是/
def calculate(self, a, operator, b):
# write your code here
if operator == '+':
return a + b
elif operator == '-':
return a - b
elif operator == '*':
return a * b
elif operator == '/':
return a // b
- 三数之中的最大值
def maxOfThreeNumbers(self, num1, num2, num3):
# write your code here
if num1 > num2:
if num1 > num3:
return num1
else:
return num3
else:
if num2 > num3:
return num2
else:
return num3
- 大小写转换
注意转化成ascii码后比较,转换大小写
def lowercaseToUppercase(self, character):
# write your code here
return chr(ord(character