Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bijay-shrestha/9375f476e23df8ce4cfd7e9f30335803 to your computer and use it in GitHub Desktop.
Save bijay-shrestha/9375f476e23df8ce4cfd7e9f30335803 to your computer and use it in GitHub Desktop.
package com.basic.practice;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class OddNumberFollowedBySquareOfIt {
public static void main(String[] args) {
// int[] arrayOfNumbers = {1, 3, 4, 6, 5, 25};
int[] arrayOfNumbers = {1, 3, 4, 6, 5, 0};
log.info("Checking if at least 1 odd number in array {} is followed by it's square. Return 1 for Yes and 0 for No.",
arrayOfNumbers);
log.info("Actual Result: {}", checkIfAnOddNumberIsFollowedBySquare(arrayOfNumbers));
}
static int checkIfAnOddNumberIsFollowedBySquare(int[] a) {
int len = a.length;
for (int i = 0; i < len - 1; i++) {
if (a[i] % 2 != 0) {
if (a[i] * a[i] == a[i + 1]) {
return 1;
}
}
}
return 0;
}
}
@sanjmgr
Copy link

sanjmgr commented Aug 19, 2022

Here is my solution, instead of making nested if condition, lets use chaining with &&

private static int oddNumberFollowedBySquareOfIt(int[] arrayOfNumbers) {

    for (int i = 0; i < arrayOfNumbers.length; i++) {
        if (arrayOfNumbers[i] % 2 != 0 && arrayOfNumbers[i + 1] == arrayOfNumbers[i] * arrayOfNumbers[i]) {
            System.out.println("index are: [ " + i + ", " + (i + 1) + " ]");
            return 1;
        }
    }

    return 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment