简体   繁体   中英

How to find a binary gap within a positive number n. Find the maximum length of the binary gap of the number

public int solution(int N) {
    string result ="";
    int MaxLength =0;
    while (N > 0) {
        int remainder = N%2;
        result = remainder.ToString() + result;
        N/=2;
    }

    if(result != ""){
        string [] strArr = result.Split('1');
        if(strArr.Length >2){
            foreach(string str in strArr){
                if(str.Length > MaxLength)
                    MaxLength = str.Length;
            }
        }
    }
    return MaxLength;
}

This code returns the maximum of the binary gap within a positive number. A binary gap is actually the maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

This code takes into account the highl bit of negative numbers and works a little faster :)

public static int SolutionV2(int N)
    {
        int MaxLength =0;

        string strArray = Convert.ToString(N, 2);
        int count = 0;
        bool beginCounter = false;
        foreach(char bit in strArray)
        {
            if(bit == '1')
            {
                if (MaxLength < count) { MaxLength = count; }
                count = 0;
                beginCounter = true;
            }
            else
            {
                if (beginCounter) { count++; }
            }
        }
        return MaxLength;
    }
public int solutionV3(int N) {
    string result = Convert.ToString(N, 2);
    int MaxLength =0;

    if(result != ""){
        string [] strArr = result.Split('1');
        if(strArr.Length >2){
            foreach(string str in strArr){
                if(str.Length > MaxLength)
                    MaxLength = str.Length;
            }
        }
    }
    return MaxLength;
}

Refactor code version you can use this code to get the max length of a binary gap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM