leetcode笔记--3 Niim game

question:

You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.

Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.

For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.

1 怎么计算，有些糊涂

2 python 除法

1.整数除法

``````>>>-1/10
-1``````

``````>>>int(float(-1)/10)
0``````

2.取余

Java和Python整数除法都遵循下面这个公式：

``(a/b)*b+c=a``

``a mod b=c=a-(a/b)*b``

``````For Java: -2 % 3==-2
For Python: -2 % 3==1```
```

``````def func(a):
pos, res=1, []
while a/pos:
res+=(a/pos)%10,
pos*=10
return res``````

Java代码也差不多就是这样了。但如果输入的整数是一个负数，Java版本的代码还是可以得到正确的结果，而Python不能（曾经在这里被坑的，举手）。那怎样用Python正确地搞定这个问题嘞？可以先去绝对值和符号，当正数来处理，最后再在结果里搭上符号。

3. Follow-ups

3.1 Python中的另一个除法操作

``````>>>1.0/2
0.0
>>>1.0//2.0
0.0
>>>1//2
>0``````

``````>>>divmod(7, 2)
(3, 1)
>>>divmod(7.0, 2)
(3.0, 1.0)``````

3.2 Python中的舍入

Floor rounding:

``````>>>import math
>>>math.floor(1.2)``````
``````1.0
>>>math.floor(-1.2)
-2.0``````

Ceiling rounding:

``````>>>math.ceil(1.2)
2.0
>>>math.ceil(-1.2)
-1.0``````

Round-off:

``````>>>round(0.5)
1.0
>>>round(-0.4)
-0.0
>>>round(-0.5)
-1.0``````

``````>>>round(0.21, 1)
0.2
>>>round(0.21, 2)
0.21``````

Caution !

``````>>>round(2.675, 2)
2.67``````

``````>>>0.1+0.2
0.30000000000000004``````

`2.67499999999999982236431605997495353221893310546875`，第三位小数是4，那么round(2.675, 2)就相当于round(2.674, 2)，结果当然是2.67。值得注意的是，这种现象是广泛存在于各种计算机和各种编程语言的，不是bug，只是有的语言选择了不让你看到。

leetcode笔记

leetcode 笔记 Linked List 2. Add Two Numbers You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a

LeetCode 笔记26 Single Number II

Given an array of integers, every element appears three times except for one. Find that single one. Note:Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 没辙,智商碾压题.楼主没遇到之前就只会这种做法. public int si

LeetCode 笔记28 Maximum Gap

Given an unsorted array, find the maximum difference between the successive elements in its sorted form. Try to solve it in linear time/space. Return 0 if the array contains less than 2 elements. You may assume all elements in the array are non-negat