[Codility] Lession 1.1 Binary Gap

Swift Solution

public func solution(num : Int) -> Int {

    // Since the number under 4 do not have any binary gap, so just simply return 0
    guard num > 4 else { return 0 }
    // Convert the Integer to binary string
    let binaryStr = String(num, radix:2)
    // Manipulate binary string to character array
    let strArray = [Character](binaryStr.characters)

    var startIdx = 0
    var tracking = false
    
    var maxGap = 0
    
    for i in 0 ..< strArray.count
    {
       // Ignore all the '0' until find the first '1'
        if (strArray[i] == "1") && (tracking == false){
            startIdx = i
            tracking = true
        }
        else if (strArray[i] == "1") && (tracking == true){
            
            let tempGap = (i - startIdx - 1)
            //Compare each binary gap and compare to saved max gap
            maxGap = (tempGap > maxGap) ? tempGap : maxGap
            //Re tag the starting index for next search
            startIdx = i
        }
    }
    return maxGap
}

Objective-C Solution

- (int) binaryGap:(int) num {

    if(num <= 4) {return 0;}
    
    NSString*binaryStr = [self binaryStringFromInteger:5];
    
    int strCount = (int)binaryStr.length;
    
    int startIdx = 0;
    
    BOOL tracking = false;
    
    int maxGap = 0;
    
    for (int i = 0; i < strCount; i++) {
        if ([binaryStr characterAtIndex:i] == '1' && (!tracking)) {
            startIdx = i;
            tracking = true;
        }
        else if([binaryStr characterAtIndex:i] == '1' && (tracking)) {
            int tempGap = (i - startIdx - 1);
            if (tempGap > maxGap) { maxGap = tempGap; }
            startIdx = i;
        }
    }
    return maxGap;
}

-(NSString*) binaryStringFromInteger:(int) number
{
    NSMutableString * string = [[NSMutableString alloc] init];
    
    int spacing = pow( 2, 3 );
    int width = ( sizeof( number ) ) * spacing;
    int binaryDigit = 0;
    int integer = number;
    
    while( binaryDigit < width )
    {
        binaryDigit++;
        [string insertString:( (integer & 1) ? @"1" : @"0" )atIndex:0];
        integer = integer >> 1;
    }
    return string;
}

你可能感兴趣的:([Codility] Lession 1.1 Binary Gap)