首页 > 代码库 > arranging-coins

arranging-coins

https://leetcode.com/problems/arranging-coins/

public class Solution {
    public int arrangeCoins(int n) {
        // n >= x*(x+1)/2; 2n >= x^2 + x; 8n+1 >= 4x^2 + 4x + 1 = (2x+1)^2
        // (8n+1)^(1/2) = 2x+1; x = ((8n+1)^(1/2)-1)/2;
        // 注意下面的n要转成long,不然可能溢出
        return (int)(Math.sqrt(8*(long)n+1)-1)/2;
    }
}

 

arranging-coins