-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathDay06.java
149 lines (112 loc) · 2.22 KB
/
Day06.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
package com.offer;
public class Day06 {
private static int[] array = {
1,1,1,1,0,1,1,1,1
};
/**
* 旋转数组查最小值
* @author kexun
*
*/
public int min(int[] array) {
int start = 0;
int end = array.length - 1;
int min = 0;
while (end - start > 1) {
if (array[start] > array[end]) {
int mid = (start+end)/2;
int mvalue = array[mid];
if (array[start] > mvalue) {
end = mid;
}
if (array[start] <= mvalue) {
start = mid;
}
} else if (array[start] == array[end]) {
min = array[start];
for (int i = start+1; i <= end; i++) {
if (min > array[i])
min = array[i];
}
return min;
}
}
if (array[start] > array[end]) {
min = array[end];
} else {
min = array[start];
}
return min;
}
/**
* 递归调用, 但效率不可接受
* @param n
* @return
*/
public int fibo(int n) {
System.out.println(n);
if (n <= 0)
return 0;
if (n == 1)
return 1;
return fibo(n-1) + fibo(n-2);
}
/**
* 位运算 统计一个数的二进制表示法中 1的个数
* @param n
* @return
*/
public int numberOf1(int n) {
int count = 0;
while (n != 0) {
if ((n&1) == 1) {
count++;
}
n = n >> 2;
}
return count;
}
/**
* 考虑到负数的情况
* @param n
* @return
*/
public int negNumberOf1(Integer n) {
int count = 0;
int index = 1;
while (index != 0) {
int value = (n & index);
if ((n & index) != 0) {
count++;
}
index = index << 1;
}
return count;
}
/**
* 把原数值-1 再通过&操作 能计算出有多少个1
* @param n
* @return
*/
public int numOf1(int n) {
int count = 0;
while (n != 0) {
count++;
System.out.println(Integer.toBinaryString(n));
n = (n - 1)&n;
}
return count;
}
public static void main(String[] args) {
Day06 d = new Day06();
// int min = d.min(array);
// System.out.println(min);
// int fibo = d.fibo(20);
// System.out.println(fibo);
System.out.println(d.numberOf1(1));
System.out.println(d.negNumberOf1(-2));
System.out.println(d.numberOf1(3));
System.out.println(d.numberOf1(4));
System.out.println(d.numOf1(-5));
}
}