File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .imooc .activiti .helloworld ;
2+
3+ import java .io .BufferedReader ;
4+ import java .io .IOException ;
5+ import java .io .InputStreamReader ;
6+
7+ /**
8+ * @author shironghui on 2019/4/18.
9+ */
10+
11+
12+ class Solution14 {
13+ /**
14+ * 让我们按一定规律排列,第一行放1个,第二行放2个,以此类推,
15+ * 问我们有多少行能放满。通过分析题目中的例子可以得知最后一行只有两种情况,放满和没放满。
16+ * 由于是按等差数列排放的,我们可以快速计算出前i行的硬币总数。
17+ * 我们先来看一种O(n)的方法,非常简单粗暴,就是从第一行开始,一行一行的从n中减去,
18+ * 如果此时剩余的硬币没法满足下一行需要的硬币数了,我们之间返回当前行数即可
19+ * @param n
20+ * @return
21+ */
22+ public int arrangeCoins (int n ) {
23+ for (int i =1 ;i <Integer .MAX_VALUE ;i ++){
24+ if (n >=0 ){
25+ n =n -i ;
26+ }
27+ else {
28+ return i -2 ;
29+ }
30+ }
31+ return -1 ;
32+ }
33+ }
34+
35+ public class TestArrangeCoins {
36+ public static void main (String [] args ) throws IOException {
37+ BufferedReader in = new BufferedReader (new InputStreamReader (System .in ));
38+ String line ;
39+ while ((line = in .readLine ()) != null ) {
40+ int n = Integer .parseInt (line );
41+
42+ int ret = new Solution14 ().arrangeCoins (n );
43+
44+ String out = String .valueOf (ret );
45+
46+ System .out .print (out );
47+ }
48+ }
49+ }
You can’t perform that action at this time.
0 commit comments