You have a total of n coins that you want to form in a staircase shape, where every kth row must have exactly k coins.
Given n, find the total number of full staircase rows that can be formed.
Given n, find the total number of full staircase rows that can be formed.
Example 1:
n = 5
The coins can form the following rows:
*
* *
* *
Because the 3rd row is incomplete, we return 2.
Approach
Java
public class ArrangeCoins {public static void main(String[] args) {int n = 1;System.out.println(arrangeCoins(n));}public static int arrangeCoins(int n) {int i = 1;int cnt = 0;while (i <= n) {cnt++;n = n - i;i++;}return cnt;}}
C++
#include <bits/stdc++.h>using namespace std;//function to arrange coinsint arrangeCoins(int n){int i=1;int cnt=0;while(i<=n){cnt++;n=n-i;i++;}return cnt;}int main(){int n=5;cout<<arrangeCoins(n);cout<<"\n";return 0;}
No comments:
Post a Comment