Problem:

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.

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.

Hint:

If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?

Code:

class Solution {
public:
bool canWinNim(int n) {
return !(n % 4 == 0);
}
};

说明:

这里用到的是1+3=4,就是当4出现在你面前时,你必失败,这样的话,每多一个4,你的对手都会将他消除,所以,只要是4的倍数,就必输。而只要不是4的倍数,你就可以将它变成4的倍数,从而必胜。

Problem

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

Example:

Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3

Code

class NumArray {
public:
NumArray(vector<int> &nums) {
data = nums;
} int sumRange(int i, int j) {
if (i < 0 || j >= data.size() || i > j) {
return 0;
}
int result = 0;
for (int k = i; k <= j; k++) {
result += data[k];
}
return result;
}
private:
vector<int> data;
}; // Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);

说明:

这个应该没啥可说的,就是初始化好了,取相应下标之间的数作和,不过第一次提交失败了,踩了java的坑了,定义成员变量用的是nums,直接this.nums了,,应该是this->nums的。

感觉似乎有点与初衷相悖了,因为总是从自己的私库里取东西发表,应该写新的的。

最新文章

  1. 微信支付:H5吊起支付API,不显示&ldquo;确认支付、输入密码&rdquo;界面
  2. [WCF编程]12.事务:服务事务编程(下)
  3. swiper 技巧
  4. C#中的 正则表达式
  5. 配置 Sublime Text 用 Node.js 执行 JavaScript 程序
  6. jQuery$命名冲突问题解决方法
  7. BZOJ 1208 宠物收养所
  8. python实现中文图片文字识别--OCR about chinese text--tesseract
  9. C++使用简单的函数指针
  10. MFC 控件用法
  11. Django - 通用视图
  12. MySql学习(七) —— 查询性能优化 深入理解MySql如何执行查询
  13. 黑马day16 jquery&amp;amp;内容过滤选择器&amp;amp;可见度选择器
  14. display:flex布局
  15. List集合2-LinkedList
  16. jenkins 使用curl调用时带文件参数
  17. localstorage和vue结合使用2
  18. springboot 学习之路 14(整合mongodb的Api操作)
  19. 安装Jenkins服务
  20. c# 主机和网络字节序的转换 关于网络字节序和主机字节序的转换

热门文章

  1. [leetcode] 2. Pascal&#39;s Triangle II
  2. css 三彩loading
  3. /Date(1512551901709+0800)/转换
  4. php从文本读入数据,处理结果再导入到文本
  5. [ActionScript 3.0] 翻牌效果,运用语法rotationY,PerspectiveProjection
  6. [ActionScript 3.0] AS利用ByteArray向PHP发送二进制数据生成图片
  7. 如何实现 Python 中 selnium 模块的换行
  8. H5新手教程,小白来看看。
  9. CentOS6.9 ARM虚拟机扩容系统磁盘
  10. 10分钟教你用Python实现微信自动回复