Swift bit manipulation


  • 0
    C
    func CaculateBitNumber( input_num:Int )->Int
    {
    	var count = 0, value = input_num;
    	
    	while( value != 0 )
    	{
    		if( ( value & 0x1 ) == 1 )
    		{
    			count += 1
    		}	
    		value >>= 1
    	}
    	
    	return count
    }
    
    class Solution {
        func readBinaryWatch(_ num: Int) -> [String] 
        {
            var result = [String]( ) 
            var n = 1, m = 0    
            var combstring1:String = "", combstring2:String = ""
            
            if( num > 8 )
            {
                return result
            }
            
            for index4 in 0...11
            {
            	m = CaculateBitNumber( input_num:index4 )
            	
            	if( num >= m )
            	{
            		combstring1 += "\(index4):"
            		
            		n = num - m
            		
            		for index6 in 0...59
            		{
            			m = CaculateBitNumber( input_num:index6 )
            			
            			if( n == m )
            			{
            				if( ( index6 >= 0 ) && ( index6 <= 9 ) )
            				{
            					combstring2 += "0\(index6)"
            				}
            				else
            				{
            					combstring2 += "\(index6)"
            				}
            				
            				result.append( combstring1 + combstring2 )
            				combstring2 = ""
            			}
            		}
            		
            		combstring1 = ""
            	}
            }
            
            return result
        }
    }
    

Log in to reply
 

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