[Java, C++] Count 1's | O(NM) Explanation
Algorithm:\nCount the number of ones in each string and then multiply the count of consecutive ones and add it to the ans:\nLets first do it in O(n) space in or
**Algorithm:**\nCount the number of ones in each string and then multiply the count of consecutive ones and add it to the ans:\nLets first do it in O(n) space in order to understand what exactly we\u2019re doing:\n\n<iframe src="https://leetcode.com/playground/YjcAYtMx/shared" frameBorder="0" width="600" height="300"></iframe>\n\n**Space optimised O(1):**\nAs we can observe from the above solution, we just need to keep track of previous count of one and we can simply multiply the current count one to the previous count and add it to answer. After that our current count will be the old count for the next coming string.\n\n```\npublic int numberOfBeams(String[] bank) {\n        int pOnes=0; int res=0;\n        for(String s: bank){\n            int count=0;\n            for(char ch: s.toCharArray()){\n                if(ch==\'1\'){\n                    count++;\n\t\t\t\t}\n            }\n           if(count>0){\n                res+=(count*pOnes);\n                pOnes=count;\n            }\n        }\n        return res;\n    }\n```\nUsing **Java Stream API**\n```\nclass Solution {\n    public int numberOfBeams(String[] bank) {\n        int pOnes=0; int res=0;\n        for(String s: bank){\n            int count=(int)s.chars().filter(ch->ch==\'1\').count();\n            res+=(count*pOnes);\n            if(count>0)\n                pOnes=count;\n        }\n        return res;\n    }\n}\n```\n**C++ code** by @coderaky\n```\nclass Solution {\npublic:\n    int numberOfBeams(vector<string>& bank) {\n        int pre=0,cur=0,res=0;\n        for(int i=0;i<bank.size();i++){\n            cur=count(bank[i].begin(),bank[i].end(),\'1\');\n            if(cur>0)\n                res+=pre*cur,pre=cur;\n        }\n        return res;\n    }\n};\n```
['Math', 'Java']