#1513
Medium Algorithms Number of substrings with only 1s
Math String
57.4% acceptance
Feb 25, 2026
1231
42
Given a binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 109 + 7.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn num_sub(s: String) -> i32 {
const MOD: i64 = 1_000_000_007;
let mut ans = 0i64;
let mut cnt = 0i64;
for c in s.chars() {
if c == '1' {
cnt += 1;
ans = (ans + cnt) % MOD;
} else {
cnt = 0;
}
}
ans as i32
}
}