Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created March 6, 2026 20:51
Show Gist options
  • Select an option

  • Save tatsuyax25/0a13b4a95e60e9d919c76ae30ff1df30 to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/0a13b4a95e60e9d919c76ae30ff1df30 to your computer and use it in GitHub Desktop.
Given a binary string s without leading zeros, return true if s contains at most one contiguous segment of ones. Otherwise, return false.
/**
* @param {string} s
* @return {boolean}
*/
var checkOnesSegment = function(s) {
// This flag will turn true once we hit the first '0'
// after the initial block of ones.
let seenZero = false;
// Loop through each character in the string
for (let char of s) {
if (char === '0') {
// We've reached the end of the ones segment
seenZero = true;
} else {
// char === '1'
// If we've already seen a zero and now see a '1',
// that means a second segment of ones has started.
if (seenZero) {
return false;
}
}
}
// If we never encountered a second segment of ones,
// the string is valid.
return true;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment