Microsoft Mock Interview #1

1595 ワード


こうやって出てきたらいいのに….2^^

Delete Node in a Linked List

class Solution {
    public void deleteNode(ListNode node) {
        node.val = node.next.val;
        node.next = node.next.next;
        
    }
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Delete Node in a Linked List.
Memory Usage: 38.3 MB, less than 66.17% of Java online submissions for Delete Node in a Linked List.
そうですね.

Number of 1 Bits

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        String sn = Integer.toBinaryString(n);
        int total = 0;
        for (int i = 0; i < sn.length(); i++) {
            if (sn.charAt(i) == '1') {
                total++;
            }
        }
        
        return total;
    }
}
見た途端にtoBinaryStringを思い出し、デバッグして交換しないとダメだと思っていたのですが…^^;;;;
ソリューション
public int hammingWeight(int n) {
    int sum = 0;
    while (n != 0) {
        sum++;
        n &= (n - 1);
    }
    return sum;
}
100%
public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
    int bits = 0;
    int mask = 1;
    for (int i = 0; i < 32; i++) {
        if ((n & mask) != 0) {
            bits++;
        }
        mask <<= 1;
    }
    return bits;
}
}
100%