leetcode-Array篇easy难度之三连奇数判断

关键词

连续数确认

题目描述

Given an integer array arr, return true if there are three consecutive odd 
numbers in the array. Otherwise, return false.
 

Example 1:

Input: arr = [2,6,4,1]
Output: false
Explanation: There are no three consecutive odds.
Example 2:

Input: arr = [1,2,34,3,4,5,7,23,12]
Output: true
Explanation: [5,7,23] are three consecutive odds.

博主第一次提交的代码

class Solution {
    public boolean threeConsecutiveOdds(int[] arr) {
        int oddCount = 0;
        for(int i = 0; i < arr.length; i++){
            if( isOdd(arr[i]) == true){
                if( ++oddCount == 3){
                    return true;
                }
            }else{
                oddCount = 0;
            }
        }
        return false;
    }
    public boolean isOdd(int input){
        if( (input & 1) == 1){
            return true;
        } else{
            return false;
        }
    }
}

不过if else逻辑换了一下之后,好像代码更简洁了

class Solution {
    public boolean threeConsecutiveOdds(int[] arr) {
        int oddCount = 0;
        for(int i = 0; i < arr.length; i++){
            if( isOdd(arr[i]) == false){
                oddCount = 0;
            }else if(++oddCount == 3){
                return true;
            }
            
        }
        return false;
    }
    public boolean isOdd(int input){
        if( (input & 1) == 1){
            return true;
        } else{
            return false;
        }
    }
}

你可能感兴趣的:(leetcode-Array篇easy难度之三连奇数判断)