/* 自定義代碼塊樣式 */

herrDeng網內搜尋

自訂搜尋

Ads

2025年11月16日 星期日

C++用 -1 mask法達到branchless解Leetcode1513 Number of Substrings With Only 1...


C++用 -1 mask法達到branchless解Leetcode1513  Number of Substrings With Only 1s|Py3 1-liner
其實很容易,想練功,試試一行解,或是把if分岔拿掉
[C++無分岔解請進]

----
It's actually quite easy. If you want to practice, try a one-line solution, or remove if branches.
class Solution {
public:
    const long long mod=1e9+7;
    int numSub(string& s) {
        long long ans=0, cnt=0;
        for(char c: s){
            cnt= -(c=='1') & (cnt+1);
            ans+= -(c=='1') & cnt;
        }
        return ans%mod;
    }
};

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章