﻿ Java: Find the distinct ways you can climb to the top

# Java Exercises: Find the distinct ways you can climb to the top

## Java Basic: Exercise-134 with Solution

Write a Java program to find the distinct ways you can climb to the top (n steps to reach to the top) of stairs. Each time you can either climb 1 or 2 steps.

Example: n = 5 a) 1+1+1+1+1 = 5 b) 1+1+1+2 = 5 c) 1+2+2 = 5 d) 2+2+1 = 5 e) 2+1+1+1 = 5 f) 2+1+2 = 5 g) 1+2+1+1 = 5 h) 1+1+2+1 = 5

Pictorial Presentation:

Sample Solution:

Java Code:

``````class Solution {
public static int climbStairs(int n) {
if (n <= 1) {
return 1;
}
int[] s_case = new int[n + 1];
s_case[0] = 1;
s_case[1] = 1;
for (int i = 2; i <= n; i++) {
s_case[i] = s_case[i - 1] + s_case[i - 2];
}
return s_case[n];
}
/* Driver program to test above functions */
public static void main(String[] args) {
int steps = 5;
System.out.println("Distinct ways can you climb to the top: "+climbStairs(steps));
}
}
```
```

Sample Output:

```Distinct ways can you climb to the top: 8
```

Flowchart:

Java Code Editor:

Company:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿

Share this Tutorial / Exercise on : Facebook and Twitter

## Java: Tips of the Day

countOccurrences

Counts the occurrences of a value in an array.

Use Arrays.stream().filter().count() to count total number of values that equals the specified value.

```public static long countOccurrences(int[] numbers, int value) {
return Arrays.stream(numbers)
.filter(number -> number == value)
.count();
}
```

Ref: https://bit.ly/3kCAgLb