python solution


  • 0
    X
    class Solution:
        def ipToCIDR(self, ip, n):
    
            ip = int.from_bytes(bytes(map(int, ip.split('.'))), 'big')
            
            ret = []
            
            while True:
                d = ip & (-ip)
                if d > n:
                    break
                ret.append((ip, 32-d.bit_length()+1))
                ip += d
                n -= d
            
            while n > 0:
                i = n.bit_length()
                ret.append((ip, 32-i+1))
                d = 1 << (i-1)
                ip += d
                n -= d
            
            return ['{}/{}'.format(ip2str(ip), pref) for ip, pref in ret]
    
    def ip2str(ip):
        return '.'.join(map(str, ip.to_bytes(4, 'big')))
    

Log in to reply
 

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