-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindKthNumber.java
More file actions
75 lines (68 loc) · 1.64 KB
/
Copy pathFindKthNumber.java
File metadata and controls
75 lines (68 loc) · 1.64 KB
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
package tree;
import org.junit.Test;
import java.util.Arrays;
/**
* @Author: wei1
* @Date: Create in 2019/1/31 19:04
* @Description: 字典序第k小的数字
*/
public class FindKthNumber {
@Test
public void test() {
for (int i = 1; i <= 10; i++) {
int kthNumber = findKthNumber(100, i);
System.out.println(kthNumber);
}
}
// http://www.cnblogs.com/grandyang/p/6031787.html
public int findKthNumber(int n, int k) {
int cur = 1;
int step;
k--;
while (k > 0) {
step = calStep(n, cur, cur + 1);
if (step <= k) {
k -= step;
cur++;
} else {
k--;
cur *= 10;
}
}
return cur;
}
private int calStep(int n, long n1, long n2) {
int step = 0;
while (n1 <= n) {
step += Math.min(n + 1, n2) - n1;
n1 *= 10;
n2 *= 10;
}
return step;
}
//字典排序数字1-n
public int[] lexicalOrder(int n) {
int[] res = new int[n];
int cur = 1;
for (int i = 0; i < n; ++i) {
res[i] = cur;
if (cur * 10 <= n) {
cur *= 10;
} else {
if (cur >= n) {
cur /= 10;
}
cur += 1;
while (cur % 10 == 0) {
cur /= 10;
}
}
}
return res;
}
@Test
public void test2() {
int[] ints = lexicalOrder(30);
System.out.println(Arrays.toString(ints));
}
}