Back to all solutions
#1784 - Check if Binary String Has at Most One Segment of Ones
Problem Description
Given a binary string s without leading zeros, return true if s contains at most one contiguous segment of ones. Otherwise, return false.
Solution
/**
* @param {string} s
* @return {boolean}
*/
var checkOnesSegment = function(s) {
let seenZero = false;
for (let i = 1; i < s.length; i++) {
if (s[i] === '0') {
seenZero = true;
} else if (seenZero) {
return false;
}
}
return true;
};