每日一Leet

JS之鍊金術師

34 回覆
2 Like 3 Dislike
JS之鍊金術師 2022-05-27 20:58:53
成日都冇心機操 開個po玩吓
JS之鍊金術師 2022-05-27 21:03:43

const numberOfSteps = function(num) {
    let totalStep = 0
    const runStep = (num) => {
        if(num === 0) return 
        totalStep = totalStep + 1
        const isEven = num % 2 === 0
        return runStep(isEven ? num / 2 : num -1)
    }
    runStep(num)
    return totalStep
};

大家隨便改正
程式猿 2022-05-27 21:21:16
bitcount()
算子代數 2022-05-27 21:35:41
咁多人leetcode
程式猿 2022-05-27 21:37:12
諗真啲
做愛賣仔 2022-05-27 22:37:55
const step = (num) => {
let bits = 0;
while (num > 0) {
num == num >> 1;
bits += 1;
}
return bits;
}
做愛賣仔 2022-05-27 22:39:10
sor 眼殘冇睇題目唔駛理
JS之鍊金術師 2022-05-27 22:47:58
學到嘢
做愛賣仔 2022-05-27 22:51:44
const step = (num) => {
let bits = 0;
while (num > 0) {
bits += num & 1 + 1;
num == num >> 1;
bits += 1;
}
return bits - 1;
}


num & 1 係masking,apply bitwise and 去攞least significant bit。
E.g. 5 & 1 = 101 & 001 = 1,可以用黎判斷單雙數。
num >> 1 係right shift,將bits向右移一格。
E g. 5 >> 1 = 101 >> 1 = 10 = 2,個result同math.floor(num /2)等價。
煙條14納米牙膏 2022-05-28 00:59:58
class Solution {
public:
    int numberOfSteps(int num) {
        int step=0;
        while(num!=0)
        {
            if(num%2==0)
                num/=2;
            else
                num-=1;
            step+=1;
        }
        return step;
    }
};

LM學嘢
JS之鍊金術師 2022-05-28 02:22:31
突然醒起recursion可以寫得clean啲
const numberOfSteps = function(num, totalSteps = 0) {
        if(num === 0) return totalSteps
        totalSteps = totalSteps + 1

        return numberOfSteps(num % 2 === 0 ? num / 2 : num -1, totalSteps)
};
JS之鍊金術師 2022-05-28 02:51:31
但呢條嚟講唔係好複雜好似咁寫好啲
程式猿 2022-05-28 05:12:10
special case: num = 0
柏克萊特母 2022-05-28 11:27:48
抄po狗
柏克萊特母 2022-05-28 11:28:13
走啦 js撚
唔好獻世唔該
JS之鍊金術師 2022-05-31 01:44:29
Two Sum
Given an array of integer nums and an integer target, return indices of the two numbers such that they add up to the target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]

Constraints:
- 2 <= nums.length <= 104
- -109 <= nums[i] <= 109
- -109 <= target <= 109
- Only one valid answer exists. 


Answer:
const twoSum = (nums, target, numMap={}, step=0)=> {
    if (target-nums[step] in numMap) {
            return [numMap[target-nums[step]], step]
    }
    
    numMap[nums[step]] = step
    return twoSum(nums, target, numMap, step+1)
}; 

用js唔理memory usage
吹水台自選台熱 門最 新手機台時事台政事台World體育台娛樂台動漫台Apps台遊戲台影視台講故台健康台感情台家庭台潮流台美容台上班台財經台房屋台飲食台旅遊台學術台校園台汽車台音樂台創意台硬件台電器台攝影台玩具台寵物台軟件台活動台電訊台直播台站務台黑 洞