441. Arranging Coins

You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.

Given n, find the total number of full staircase rows that can be formed.

n is a non-negative integer and fits within the range of a 32-bit signed integer.

Example 1:

n = 5

The coins can form the following rows:
¤
¤ ¤
¤ ¤

Because the 3rd row is incomplete, we return 2.

 

Example 2:

n = 8

The coins can form the following rows:
¤
¤ ¤
¤ ¤ ¤
¤ ¤

Because the 4th row is incomplete, we return 3.
题目含义:给定n个硬币构造等差数列,求能构成多少行 

方法一:直接遍历即可,从1开始,如果剩下是数不能构成一行则返回。注意要先判断剩下的数是否满足,而不是累加以后再判断,这样可能会导致溢出。

复制代码
1     public int arrangeCoins(int n) {
2         int i=0;
3         while (n>0)
4         {
5             i++;
6             n-=i;
7         }
8         return n==0?i:i-1;      
9     }
复制代码

 

方法二:直接求根法

(x+1)*x/2 = n

x+ x = 2n 

4x2 + 4x = 8n 

(2x+1)(2x+1) = 8n +1

x = (sqrt(8n+1) - 1)/2

 

1     public int arrangeCoins(int n) {
2         return (int)((-1.0 + Math.sqrt(1.0 + 8.0 * n)) / 2);
3     }

 

posted @   daniel456  阅读(198)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示