simple python, brief explanation


  • 0
    E

    Given a starting number, find the maximum possible number of common leading bits without exceeding an upper bound.

    class Solution(object):
        def ipToCIDR(self, ip, rng):
            """
            :type ip: str
            :type range: int
            :rtype: List[str]
            """
            res=[]
            MX=256
            
            def toip(n):
                ip = []
                while len(ip)<4:
                    ip.append(str(n%MX))
                    n/=MX
                return ".".join(reversed(ip))
            
            def toint(ip):
                n=0
                for nn in map(int,ip.split(".")):
                    n*=MX
                    n+=nn
                return n
        
            start = toint(ip)
            end = start+rng
    
            def maxcomm(start,end):
                for b in xrange(32,-1,-1):
                    mask = ((1<<b)-1)
                    if start&mask==0 and start|mask <end:
                        return 32-b, start|mask
                assert(false)
    
            while start<end:
                comm, newstart = maxcomm(start,end)
                res.append("{}/{}".format(toip(start),comm))
                start=newstart+1
            
            return res
    

Log in to reply
 

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