Sum of devices*prev count 1
Although it is labeled medium, for those who know the multiplicative principle of counting, the problem is the implementation of the following formula.\n\nsum=\
Although it is labeled medium, for those who know the multiplicative principle of counting, the problem is the implementation of the following formula.\n$$\nsum=\\sum_{devices>0}devices*prev\n$$\nwhere $prev$ denote the previous devices>0.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nImplement this formula\n\n[Please turn on English subtitles if necessary]\n[https://youtu.be/rxLCRR_gSqo?si=wbzBScj0UfzWKTSi](https://youtu.be/rxLCRR_gSqo?si=wbzBScj0UfzWKTSi)\n\nC++, Python & C codes are implememted.\n\n2nd C++ code, thanks to @wawaroutas pointing out his solution, is using exchange which is more efficient, runs in 40ms & beats 99.79%.\n\n2nd Python code is 1-liner.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(nm)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(m)$$\n\n# C++ Code 52ms Beats 99.38%\n\n```python []\nclass Solution:\n    def numberOfBeams(self, bank: List[str]) -> int:\n        ans=0\n        prev=0\n        for row in bank:\n            dev=row.count(\'1\')\n            if dev>0:\n                ans+=dev*prev\n                prev=dev\n        return ans\n```\n```C++ []\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n    int numberOfBeams(vector<string>& bank) {\n        int ans=0, prev=0;\n        for(auto& row: bank){\n            int device=count(row.begin(), row.end(), \'1\');\n            if (device>0){\n                ans+=device*prev;\n                prev=device;\n            }\n        }\n        return ans;\n    }\n};\n```\n```C []\n#pragma GCC optimize("O3", "unroll-loops")\nint numberOfBeams(char** bank, int bankSize) {\n    int ans=0, prev=0;\n    char *row;\n    for (register int i=0; i<bankSize; i++){\n        row=bank[i];\n        int dev=0;\n        for(register int j=0; row[j]!=\'\\0\'; j++)\n            dev+=(row[j]==\'1\');\n        if (dev>0){\n            ans+=dev*prev;\n            prev=dev;\n        }   \n    }\n    return ans;\n}\n\n        \n```\n# C++ using exchange is more efficient||40ms Beats 99.79%\n```\n    int numberOfBeams(vector<string>& bank) {\n        int ans=0, prev=0;\n        for(auto& row: bank){\n            int device=count(row.begin(), row.end(), \'1\');\n            if (device>0){\n                ans+=exchange(prev,device)*device;\n            }\n        }\n        return ans;\n    }\n```\n# Python 1-liner \n```\nclass Solution:\n    def numberOfBeams(self, bank: List[str]) -> int:\n        return (dev:=[row.count(\'1\') for row in bank if row.count(\'1\')]) and sum(x*y for x, y in zip(dev[1:], dev[:-1])) or 0\n```
['String', 'C', 'Combinatorics', 'Counting', 'C++', 'Python3']