# 1513. Number of Substrings With Only 1s

## Description

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.

Example 1:

Input: s = "0110111"
Output: 9
Explanation: There are 9 substring in total with only 1's characters.
"1" -> 5 times.
"11" -> 3 times.
"111" -> 1 time.

Example 2:

Input: s = "101"
Output: 2
Explanation: Substring "1" is shown 2 times in s.


Example 3:

Input: s = "111111"
Output: 21
Explanation: Each substring contains only 1's characters.


Constraints:

• 1 <= s.length <= 105
• s[i] is either '0' or '1'.

## Solutions

• class Solution {
public int numSub(String s) {
final int mod = (int) 1e9 + 7;
int ans = 0, cnt = 0;
for (int i = 0; i < s.length(); ++i) {
cnt = s.charAt(i) == '1' ? cnt + 1 : 0;
ans = (ans + cnt) % mod;
}
return ans;
}
}

• class Solution {
public:
int numSub(string s) {
int ans = 0, cnt = 0;
const int mod = 1e9 + 7;
for (char& c : s) {
cnt = c == '1' ? cnt + 1 : 0;
ans = (ans + cnt) % mod;
}
return ans;
}
};

• class Solution:
def numSub(self, s: str) -> int:
ans = cnt = 0
for c in s:
if c == "1":
cnt += 1
else:
cnt = 0
ans += cnt
return ans % (10**9 + 7)


• func numSub(s string) (ans int) {
const mod = 1e9 + 7
cnt := 0
for _, c := range s {
if c == '1' {
cnt++
} else {
cnt = 0
}
ans = (ans + cnt) % mod
}
return
}

• function numSub(s: string): number {
const mod = 10 ** 9 + 7;
let ans = 0;
let cnt = 0;
for (const c of s) {
cnt = c == '1' ? cnt + 1 : 0;
ans = (ans + cnt) % mod;
}
return ans;
}