2018年7月5日 星期四

[LeetCode挑戰]344翻轉字串,292石頭堆(拈)遊戲,258首字尾字相加兩次



344翻轉字串

https://leetcode.com/problems/reverse-string/description/ 
Write a function that takes a string as input and returns the string reversed.
Example: Given s = "hello", return "olleh".

var reverseString = function(s) {
    let remind = s.substr(2,s.length - 1);
    let first = s.substr(0,1);
    let second = s.substr(1,1);
    return remind + second + first;
};



292石頭堆(拈)遊戲

https://leetcode.com/problems/nim-game/description/
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.


n的數字 第一回合(我) 第二回合(你) 第三回合(我) 第四回合(你) 贏家
1 1
2 2
3 3
4 1、2、3 3、2、1
5 1 1、2、3 3、2、1
6 2 1、2、3 3、2、1
7 3 1、2、3 3、2、1
8 1、2、3 3、2、1 1、2、3 3、2、1


因此可得知,只要是4的倍數,第一個人就不會贏
var canWinNim = function(n) {
    return n % 4 != 0;
};



258首字尾字相加兩次

https://leetcode.com/problems/add-digits/description/

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

Example:

Input: 38
Output: 2
Explanation:
The process is like: 3 + 8 = 11, 1 + 1 = 2.
Since 2 has only one digit, return it.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

var addDigits = function(num) {
    if(num < 10 || num > 99) return;
    let seperateNum = (num) => {
        num = num.toString();
        let first = num.substr(0,1);
        let second = num.substr(1,1);
        return parseInt(first) + parseInt(second);
    }
    let firstNum = seperateNum(num);
    let seondNum = seperateNum(firstNum);
    return seondNum;
};

沒有留言:

張貼留言