python 39 ms


  • 0
    W
    class Solution(object):
        def ipToCIDR(self, ip, n):
            """
            :type ip: str
            :type n: int
            :rtype: List[str]
            """
            x=0
            for ip in ip.split('.'): x=int(ip)+x*256 # convert to decimal
    
            def long2ip(x,step):
                res=[0]*4
                for i in xrange(3,-1,-1):
                    res[i]=x&255
                    x>>=8
                n=33
                while step>0:
                    n-=1
                    step/=2
                return '.'.join(map(str,res))+'/'+str(n)
    
            res=[]
            while n>0:
                step=x&-x
                while step>n: step/=2
                res.append(long2ip(x,step))
                x+=step
                n-=step
            return res

Log in to reply
 

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