Skip to content

Latest commit

 

History

History

0441.Arranging Coins

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 

English Version

题目描述

你总共有 枚硬币,你需要将它们摆成一个阶梯形状,第 行就必须正好有 枚硬币。

给定一个数字 n,找出可形成完整阶梯行的总行数。

是一个非负整数,并且在32位有符号整型的范围内。

示例 1:

n = 5

硬币可排列成以下几行:
¤
¤ ¤
¤ ¤

因为第三行不完整,所以返回2.

示例 2:

n = 8

硬币可排列成以下几行:
¤
¤ ¤
¤ ¤ ¤
¤ ¤

因为第四行不完整,所以返回3.

解法

(1 + x) * x / 2 <= n,求解 x。

(x + 1/2)² <= 2n + 1/4,即 x <= sqrt(2n + 1/4) - 1/2

由于 2n 可能溢出,故转换为 x <= sqrt(2) * sqrt(n + 1/8) - 1/2

Python3

class Solution:
    def arrangeCoins(self, n: int) -> int:
        return int(math.sqrt(2) * math.sqrt(n + 0.125) - 0.5)

Java

class Solution {
    public int arrangeCoins(int n) {
        return (int) (Math.sqrt(2) * Math.sqrt(n + 0.125) - 0.5);
    }
}

...