LeetCode 1513: Number of Substrings With Only 1s Solution

Master LeetCode problem 1513 (Number of Substrings With Only 1s), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1513. Number of Substrings With Only 1s

Problem Explanation

Explanation

To solve this problem, we can iterate through the binary string and count the continuous sequences of 1s. For every sequence of length n, the number of substrings that can be formed using that sequence is (n * (n + 1)) / 2. We calculate this for each sequence of 1s and sum up the results to get the total number of substrings with only 1s.

Solution Code

class Solution {
    public int numSub(String s) {
        int count = 0;
        int result = 0;
        int mod = 1000000007;

        for (char c : s.toCharArray()) {
            if (c == '1') {
                count++;
            } else {
                result = (result + (count * (count + 1) / 2) % mod) % mod;
                count = 0;
            }
        }

        result = (result + (count * (count + 1) / 2) % mod) % mod;

        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1513 (Number of Substrings With Only 1s)?

This page provides optimized solutions for LeetCode problem 1513 (Number of Substrings With Only 1s) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1513 (Number of Substrings With Only 1s)?

The time complexity for LeetCode 1513 (Number of Substrings With Only 1s) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1513 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1513 in Java, C++, or Python.

Back to LeetCode Solutions