欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

剑指offer 面试64题

发布时间:2025/7/14 编程问答 46 豆豆
生活随笔 收集整理的这篇文章主要介绍了 剑指offer 面试64题 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

题目:64题

求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。

 

解法一:利用Python特性

1 # -*- coding:utf-8 -*- 2 class Solution: 3 def Sum_Solution(self, n): 4 # write code here 5 return sum(list(range(1,n+1)))

解法二:利用两个函数,一个函数充当递归函数的角色,另一个函数处理终止递归的情况,如果对n连续进行两次反运算,那么非零的n转换为True,0转换为False。利用这一特性终止递归。注意考虑测试用例为0的情况,参考自GitHub

# -*- coding:utf-8 -*- class Solution:def Sum_Solution(self, n):# write code here return self.sum(n)def sum0(self,n):return 0def sum(self,n):func={False:self.sum0,True:self.sum}return n+func[not not n](n-1)

解法三:终止递归采用逻辑与的短路特性,如下:

# -*- coding:utf-8 -*- class Solution:def Sum_Solution(self, n):# write code here return n and n + self.Sum_Solution(n-1)

 

转载于:https://www.cnblogs.com/yanmk/p/9130711.html

总结

以上是生活随笔为你收集整理的剑指offer 面试64题的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。