leetcode1529 灯泡开关 贪心

  贪心 JAVA:

    public final int minFlips(String target) {
        int len = target.length(), num = 0;
        for (int i = 0; i < len; i++) {
            char curr = num % 2 == 0 ? '0' : '1';
            if (target.charAt(i) == curr) continue;
            num++;
        }
        return num;
    }

  贪心 JS:

/**
 * @param {string} target
 * @return {number}
 */
var minFlips = function (target) {
    let len = target.length, num = 0;
    for (let i = 0; i < len; i++) {
        let current = num % 2 == 0 ? 0 : 1;
        if (target.charAt(i) == current) continue;
        num++;
    }
    return num;
};

 

posted @ 2021-05-30 09:12  牛有肉  阅读(60)  评论(0编辑  收藏  举报