File tree Expand file tree Collapse file tree 2 files changed +81
-0
lines changed Expand file tree Collapse file tree 2 files changed +81
-0
lines changed Original file line number Diff line number Diff line change
1
+ package ClimbingStairs ;
2
+
3
+ /**
4
+ * User: Danyang
5
+ * Date: 1/22/2015
6
+ * Time: 20:38
7
+ *
8
+ * You are climbing a stair case. It takes n steps to reach to the top.
9
+
10
+ Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
11
+ */
12
+ public class Solution {
13
+ /**
14
+ * basic dp
15
+ * f[i] = f[i-2]+f[i-1]
16
+ * @param n
17
+ * @return
18
+ */
19
+ public int climbStairs (int n ) {
20
+ if (n <0 )
21
+ return 0 ;
22
+ if (n ==1 )
23
+ return 1 ;
24
+ if (n ==2 )
25
+ return 2 ;
26
+
27
+ int a = 1 ;
28
+ int b = 2 ;
29
+ while (n >=3 ) {
30
+ int t = b ;
31
+ b = a +b ;
32
+ a = t ;
33
+ n --;
34
+ }
35
+ return b ;
36
+ }
37
+ }
Original file line number Diff line number Diff line change
1
+ package PowXN ;
2
+
3
+ /**
4
+ * User: Danyang
5
+ * Date: 1/22/2015
6
+ * Time: 20:11
7
+ *
8
+ * Implement pow(x, n).
9
+ */
10
+ public class Solution {
11
+ /**
12
+ * classical quick power algorithm
13
+ * Notice
14
+ * 1. walk through the steps of algorithm
15
+ * 2. x<0 case, n<0 case
16
+ * @param x
17
+ * @param n
18
+ * @return
19
+ */
20
+ public double pow (double x , int n ) {
21
+ if (n ==0 )
22
+ return 1 ;
23
+
24
+ int sign = x >0 || (n &1 )==0 ? 1 : -1 ; // common bugs
25
+ boolean inverted = n <= 0 ;
26
+ x = Math .abs (x );
27
+ n = Math .abs (n );
28
+
29
+
30
+ double ret = 1 ;
31
+ double fac = x ;
32
+ while (n >1 ) {
33
+ if ((n &1 )==1 )
34
+ ret *= fac ;
35
+ fac *= fac ;
36
+ n /= 2 ;
37
+ }
38
+ ret *= fac ;
39
+ ret *= sign ;
40
+ if (inverted )
41
+ ret = 1 /ret ;
42
+ return ret ;
43
+ }
44
+ }
You can’t perform that action at this time.
0 commit comments