Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 695b9e5

Browse files
committed
6.5 发散思维能力
1 parent 9093de3 commit 695b9e5

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

sixth/fifth/README.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# 6.5 发散思维能力
2+
3+
## 面试题46 求1+2...+n
4+
> 要求:不能使用乘除、for、while、if、else等
5+
>
6+
>方法一:使用range和sum
7+
>
8+
>方法二:使用reduce
9+
10+
```python
11+
def get_sum1(n):
12+
return sum(range(1, n+1))
13+
14+
15+
def get_sum2(n):
16+
return reduce(lambda x, y: x+y, range(1, n+1))
17+
```
18+
19+
## 面试题47 不用加减乘除做加法
20+
> 要求:不用加减乘除做加法
21+
>
22+
>方法一:使用位运算,Python中大整数会自动处理,因此对carry需要加个判断
23+
>
24+
>方法二:使用sum
25+
26+
```python
27+
def bit_add(n1, n2):
28+
carry = 1
29+
while carry:
30+
s = n1 ^ n2
31+
carry = 0xFFFFFFFF & ((n1 & n2) << 1)
32+
carry = -(~(carry - 1) & 0xFFFFFFFF) if carry > 0x7FFFFFFF else carry
33+
n1 = s
34+
n2 = carry
35+
return n1
36+
37+
38+
def add(n1, n2):
39+
return sum([n1, n2])
40+
```
41+
42+
## 面试题48 不能被继承的类
43+
>Python中不知道怎么实现不能被继承的类。以后补充代码或者原因。

0 commit comments

Comments
 (0)