Skip to content

Instantly share code, notes, and snippets.

@bijay-shrestha
Created May 22, 2021 12:51
Show Gist options
  • Save bijay-shrestha/83d4e48df3fd408ebf27c8890a150b2a to your computer and use it in GitHub Desktop.
Save bijay-shrestha/83d4e48df3fd408ebf27c8890a150b2a to your computer and use it in GitHub Desktop.
A stacked number is a number that is the sum of the first n positive integers for some n.
package com.hawa.practice;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class StackedNumber {
public static void main(String[] args) {
int number = 7;
log.info("Checking if given number {} is stacked or not. " +
"--> Result: 1 for yes and 0 for no.",
number);
log.info("Actual result: {}", isStacked(number));
}
static int isStacked(int n) {
int sum = 0;
for (int i = 1; i < n; i++) {
sum += i;
if (sum == n) {
log.info("Sum {} matched on {} iteration!", sum, i);
return 1;
}
if (sum > n) break;
}
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment