LeetCode ---- Nim Game (Java/Lua 实现)
来源:互联网 发布:隔音窗户 知乎 编辑:程序博客网 时间:2024/05/22 13:48
题目:
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.
大概翻译下:
桌上有一堆石头,你和你朋友玩游戏,规则如下,你和你的朋友(另一个人,总共 2 人)轮流每次拿走 1-3 块石头,谁拿走最后的石头就是胜者。你将第一个开始拿走石头。
设计一个程序分析总共多少块石头的情况下你能赢得比赛。
比如,如果有 4 块石头,那么你永远不可能赢得比赛,因为不管你是拿 1 块、2块,还是3块,最后的时候都是你朋友拿走的。
提示:如果堆中有 5 个石头,怎么样取你才能获胜?
5 块的时候,你先拿 1 块,然后剩下 4 块,根据题目中的样例,你会发现在剩 4 块时候,谁先拿谁就输了。
归纳分析,在石头为 4 的倍数时,先手就会失败。
Java 语言实现:
public static boolean canWinNim(int n) { if (n % 4 == 0) return false; return true;}
Lua 语言实现:
function canWinNim(nums) assert(type(nums) == "number", "arguments num is not a number") return nums % 4 ~= 0 end print(canWinNim(1))
注意到 lua 语法:
- 非是 ~,而不是 Java 中的 !
- Lua 动态类型语言,数值才是有类型的,变量无类型(Java 传入参数 int n,而 lua 直接 nums)
1 0
- LeetCode ---- Nim Game (Java/Lua 实现)
- leetcode 之Nim Game java实现
- [leetcode-292]Nim Game(java)
- Leetcode: 292. Nim Game (Java)
- leetcode 292 Nim Game JAVA
- LeetCode 292 -Nim Game ( JAVA )
- LeetCode-292. Nim Game-Java
- LeetCode 292. Nim Game(Java)
- LeetCode-292. Nim Game (Java)
- leetcode之Nim Game C++实现
- leetcode之Nim Game C语言实现
- (java)leetcode problem192 Nim Game
- Nim Game leetcode 292
- leetcode Nim Game
- [LeetCode 292] Nim Game
- leetcode | Nim Game
- leetcode 292---NIM GAME
- [leetcode] 292.Nim Game
- mac 更新到macos sierra 系统后idea的svn不可用解决办法
- Mysiam与Innodb的区别
- 关于分布式事务、两阶段提交协议、三阶提交协议
- Xocde 导入其他工程
- Java设计模式----单例设计模式
- LeetCode ---- Nim Game (Java/Lua 实现)
- 87. Scramble String
- mysql while,loop,repeat循环,符合条件跳出循环
- []欢迎使用CSDN-markdown编辑器
- Ext.app.Controller.onLaunch方法介绍。
- NandFlash、NorFlash、DataFlash、SDRAM
- QT使用QJson生成解析,简单的JSON,复杂的Json使用方法
- Android自定义View分享——一个水平的进度条
- 测试markdown