• 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     }
  • 相关阅读:
    开启线程及线程锁、线程安全
    普通验证码的简单识别
    守护进程
    主动开启进程与join方法
    winForm调用WebApi程序
    使用itextsharp组件剪切PDF文件输出流文件
    通过winform窗体实现摇号
    Api程序接口对接
    C#创建txt文件并写入内容
    打印dot模板自动添加表格
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7701474.html
Copyright © 2020-2023  润新知