Python Solution (error)


  • 0
    J

    Here is my solution:

    class Solution:
        def ipToCIDR(self, ip, range):
            """
            :type ip: str
            :type range: int
            :rtype: List[str]
            """
            # covert ip to binary representation
            segs = ip.split('.')
            ip_int = (int(segs[0]) << 24) + (int(segs[1]) << 16) + (int(segs[2]) << 8) + int(segs[3])
            left = range
            ip_result = []
            masks = []
            while left > 0:
                right_most_one = self.get_right_most_one(ip_int)
                ip_result.append(ip_int)
    
                if 2 ** right_most_one > left:
                    # find the right most one that could satisfy the requirement
                    import math
                    right_most_one = math.ceil(math.log(left, 2))
                masks.append(32 - right_most_one)
                ip_int += (1 << right_most_one)
                left -= 2**right_most_one
    
            result = []
            all_ones = 0b11111111
            for i, m in zip(ip_result, masks):
                print(bin(i))
                n_ip = str((i >> 24) & all_ones) + '.' + str((i >> 16) & all_ones) + '.' + \
                       str((i >> 8) & all_ones) + '.' + str(i & all_ones)
                result.append(n_ip + '/' + str(m))
    
            return result
    
        def get_right_most_one(self, num):
            mask = 1
            index = 0
            while (num & mask) == 0:
                mask <<= 1
                index += 1
    
            return index
    

    For input: ip = '117.145.102.62', r = 8, this gives result ['117.145.102.62/31', '117.145.102.64/29']. But the expected answer is ["117.145.102.62/31","117.145.102.64/30","117.145.102.68/31"].

    Don't know why.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.