Number of Substrings With Only 1s LeetCode solution in C++
1class Solution {2/*3To calculate the substring the formula is (n*n+1)/2 so just find the range and4calculate the substrings.5*/6int mod = 1e9 + 7;7long calculateNumbeOfSubstrings(string &s, int &l, int &r) {8long range = r - l;9long ans = range * (range + 1) / 2;10return ans;11}1213public:14int numSub(string s) {15int ans = 0;16int len = s.size();17int r = 0, l = 0;18while (r < len) {19while (r < len && s[l] != '1') {20l++;21r++;22}23while (r < len && s[r] != '0') {24r++;25}26ans = (ans + calculateNumbeOfSubstrings(s, l, r)) % mod;27l = r;28}29return ans;30}31};