Search This Blog

2026/08/10

Javascript:Find first occurance of 1 in string of zeros followed by 1





Find first occurance of 1 in string of zeros followed by 1s.

Code:
    let s="00000001"
    let left =0;
    let right = s.length-1;
    let ans = -1;

    while(left<=right){
        let mid = Math.floor((left+right)/2);

        if (s[mid]==="1"){
            right = mid-1;
            ans = mid;//it change value of answer progressively
        }else{
            left = mid+1;
        }

    }

    console.log('Ans =',ans)

Output:
    Ans = 7

Explanation:
Purpose: find the index of the first 1 in a string of zeros then ones.
How: binary search check middle; if it's 1, save index and search left; if 0, search right.

Result: for s = "00000001" prints Ans = 7; returns -1 when no 1 is found. 

No comments:

Post a Comment