Skip to content

Instantly share code, notes, and snippets.

@Youngestdev
Created November 23, 2019 17:48
Show Gist options
  • Select an option

  • Save Youngestdev/e4e04c7e34a15b4027fd17edcfdb0506 to your computer and use it in GitHub Desktop.

Select an option

Save Youngestdev/e4e04c7e34a15b4027fd17edcfdb0506 to your computer and use it in GitHub Desktop.
Leetcode mock interview 1.

1

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:


Input: 4
Output: false 
Explanation: 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.

My solution:

class Solution:
    def canWinNim(self, n: int) -> bool:
        if n % 4 == 0:
            return False
        return True

2

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

Note: 0 ≤ x, y < 231.

Example

Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

The above arrows point to positions where the corresponding bits are different.

My Solution

It is a python representation of this -https://letstalkalgorithms.com/calculate-the-hamming-distance-between-two-integers/. i.e, I have to study Bits too.

class Solution:
    def hammingDistance(self, x: int, y: int) -> int:

        hammingDistance = x ^ y

        setBits = 0
            
        for i in range(0, 33):
            setBits += (hammingDistance >> i)  & 1
        return setBits
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment