77. The algorithm is simple and swift coin arrangement

You have a total of n coins, you need to put them into the shape of a ladder, the k-th row must have exactly k coins.

Given a number n, to find the full number of rows can be formed in a stepped line.

n is a nonnegative integer, and in the range of 32-bit signed integer in.

Example 1:

n = 5

Coins can be arranged in the following lines:
¤
¤ ¤
¤ ¤

Because the third row is not complete, so the return 2.
Example 2:

n = 8

Coins can be arranged in the following lines:
¤
¤ ¤
¤ ¤ ¤
¤ ¤

Because the fourth row is not complete, it returns 3.

solution:
 

   func arrangeCoins(_ n: Int) -> Int {
         guard n > 0 else {
            return 0
        }
        var n = n
        var num = 1
        while n > 0 {
            if num > n {
                n = 0
            }else{
                n = n - num
                num += 1
            }
           
        }
        return num-1
    }

 

Guess you like

Origin blog.csdn.net/huanglinxiao/article/details/93459601