Mock Interview: Adobe #2

2139 ワード


Reverse Integer

class Solution {
    public int reverse(int x) {
        if (x > Integer.MAX_VALUE || x < Integer.MIN_VALUE) {
            return 0;
        }
        
        int result = 0;
        int sign = (x < 0) ? -1 : 1;
        
        int xs = x * sign;
        
        while (xs > 0) {
            if (result > Integer.MAX_VALUE / 10) {
                return 0;
            }
            
            result = result * 10;
            result += xs % 10;
            
            xs = xs / 10;
        }
        
        return result * sign;
    }
}
Runtime: 1 ms, faster than 100.00% of Java online submissions for Reverse Integer.
Memory Usage: 36.4 MB, less than 22.51% of Java online submissions for Reverse Integer.
解けないので、この100%はbit操作が分からないので間違いだと確信しています.
最後は結果記号ではありません...xs signに戻るべきではないことに気づきました^^
火線でたぶん解けた.
class Solution:
    def reverse(self, x: int) -> int:
        
        if (x > 2**31 - 1 or x < -1 * 2**31):
            return 0
        
        result = 0
        sign = 1
        
        if x < 0:
            sign = -1
        
        xs = x * sign
        
        while xs > 0:
            if (result > 2**31 / 10):
                return 0
            result = result * 10
            result = result + xs % 10
            xs = xs / 10
        
        return result * sign

Array Partition I

class Solution {
    public int arrayPairSum(int[] nums) {
        //wtf..? sum of largest nums.length / 2 elements?
        
        
        Arrays.sort(nums);
        int result = 0;
        for (int i = 0; i < nums.length / 2; i++) {
            result += nums[i * 2];
        }
        
        return result;
    }
}
Runtime: 10 ms, faster than 97.12% of Java online submissions for Array Partition I.
Memory Usage: 41.3 MB, less than 21.39% of Java online submissions for Array Partition I.
2位の友達だけが集まって追加~