407 · 加一 与 1300 · 巴什博弈

407 · 加一
描述
给定一个非负数,表示一个数字数组,在该数的基础上+1,返回一个新的数组。

该数字按照数位高低进行排列,最高位的数在列表的最前面。

样例
样例 1:

输入:[1,2,3]
输出:[1,2,4]
样例 2:

输入:[9,9,9]
输出:[1,0,0,0]

题解:

public class Solution {
    /**
     * @param digits: a number represented as an array of digits
     * @return: the result
     */
    public int[] plusOne(int[] digits) {
        // write your code here
        long res = 0;
        for(int i = 0;i < digits.length;i++){
            res = res * 10 + digits[i];
        }  // 数组变成长整数,防止越界
        res ++;
        int[] ans = new int[String.valueOf(res).length()];  //整数转字符串
        int pos = ans.length - 1; 
        while(res > 0){
            long temp = res%10;
            ans[pos--] = (int)temp;
            res /= 10; 
        }
        return ans;
    }
}

该题需要注意int的范围与long的范围
前者int范围:-2147483648 ~ 2147483647 [-2^31 ~ 2 ^31-1 ]
后者long范围:long类型是64位的也就是 ”-2^64“ 到”2^64 -1“,给定测试用例可能越界,所以定义了res变量。

1300 · 巴什博弈
描述
你正在和朋友玩一个游戏:桌子上有一堆石头,每一次你们都会从中拿出1到3个石头。拿走最后一个石头的人赢得游戏。游戏开始时,你是先手。

假设两个人都绝对理性,都会做出最优决策。给定石头的数量,判断你是否会赢得比赛。

举例:有四个石头,那么你永远不会赢得游戏。不管拿几个,最后一个石头一定会被你的朋友拿走。

样例
样例 1:

输入:n = 4 
输出:False
解析:先手取走1,2或者3,对方都会取走最后一个
样例 2:

输入:n = 5 
输出:True
解析:先手拿1个,必胜
public class Solution {
    /**
     * @param n: an integer
     * @return: whether you can win the game given the number of stones in the heap
     */
    public boolean canWinBash(int n) {
        // Write your code here
        if( n % 4 != 0){
            return true;  // n%(m+1)!=0  胜  n为一堆石头总数  m为允许每次拿的数量
        }
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值