codeegginterviewgroup / CodeEggDailyInterview

码个蛋每日面试题
393 stars 55 forks source link

有五个布尔值,当全为true时或全为false时为true,其他为false,如何判断?当有n个时呢? #131

Open kukyxs opened 4 years ago

kami-zeros commented 4 years ago

目前我的思路是通过for循环进行判断,大家有其他想法也可以提出来: 代码如下:

/**
* @return true:全为true或全为false,
*         false:有一个不同时。
*/
 public static boolean checkSameBoolean(List<Boolean> list) {
        int m = 0;
        for (int i = 0; i < list.size(); i++) {
            Boolean aBoolean = list.get(i);
            if (aBoolean) {
                m++;
            } else {
                m--;
            }
        }
        return Math.abs(m) == list.size();
 }
kukyxs commented 4 years ago

提供一种更方便的方法

    fun checkSameBoolean(values: MutableList<Boolean>): Boolean {
        require(values.isNotEmpty()) { "List can't be empty" }

        val first = values[0]

        values.filterNot { it == first }.forEach { _ -> return false }

        return true
    }
sth0409 commented 4 years ago
private boolean check(List<Boolean> booleans) {
    boolean first = booleans.get(0);
    for (int i = 0; i < booleans.size(); i++) {
        if (booleans.get(i) != first) {
            return false;
        }
    }
    return true;
}

写出来发现和楼上一样 kotlin简洁些