구글에서 신입사원들에게 이런 문제를 냈다고 합니다.
"1에서 10000까지에서 8이 몇개 들어있을까요?"
1 import java.util.regex.Matcher;
2 import java.util.regex.Pattern;
3
4
5 public class _2012_06_30_googleInterview {
6
7 public static void main(String[] args) {
8 int usedCount = getUsedCount(1, // Range Start Number
9 10000, // Range Last Number
10 8); // Detecting Number
11 System.out.println(String.format("Count : %d", usedCount));
12 }
13
14 private static int getUsedCount(int rangeStartNum, int rangeLastNum, int detectNum) {
15 Pattern p =Pattern.compile(Integer.toString(detectNum));
16
17 int usedCount = 0;
18
19 for (int targetNum = rangeStartNum; targetNum <= rangeLastNum; targetNum++) {
20 Matcher m =p.matcher(Integer.toString(targetNum));
21 int foundMatchCount =getMatchCount(m);
22 usedCount += foundMatchCount;
23
24 // if (foundMatchCount != 0) {
25 // System.out.println(String.format("Target:[%d]\tDectedNum:[%d]\tGroupCount:[%d]", targetNum, detectNum, usedCount));
26 // }
27 }
28 return usedCount;
29 }
30
31 private static int getMatchCount(Matcher m) {
32 int matchCount = 0;
33 while (m.find()) {
34 matchCount ++;
35 }
36 return matchCount;
37 }
38
39 }
40
2 import java.util.regex.Pattern;
3
4
5 public class _2012_06_30_googleInterview {
6
7 public static void main(String[] args) {
8 int usedCount = getUsedCount(1, // Range Start Number
9 10000, // Range Last Number
10 8); // Detecting Number
11 System.out.println(String.format("Count : %d", usedCount));
12 }
13
14 private static int getUsedCount(int rangeStartNum, int rangeLastNum, int detectNum) {
15 Pattern p =Pattern.compile(Integer.toString(detectNum));
16
17 int usedCount = 0;
18
19 for (int targetNum = rangeStartNum; targetNum <= rangeLastNum; targetNum++) {
20 Matcher m =p.matcher(Integer.toString(targetNum));
21 int foundMatchCount =getMatchCount(m);
22 usedCount += foundMatchCount;
23
24 // if (foundMatchCount != 0) {
25 // System.out.println(String.format("Target:[%d]\tDectedNum:[%d]\tGroupCount:[%d]", targetNum, detectNum, usedCount));
26 // }
27 }
28 return usedCount;
29 }
30
31 private static int getMatchCount(Matcher m) {
32 int matchCount = 0;
33 while (m.find()) {
34 matchCount ++;
35 }
36 return matchCount;
37 }
38
39 }
40
'Programming > Java' 카테고리의 다른 글
측정소와 수온 (0) | 2015.02.01 |
---|---|
객체 지향의 핵심 5가지 (0) | 2014.04.13 |
[JSP] 간단 정리 (0) | 2012.04.02 |
자바 이클립스 자료 모음 (0) | 2010.02.05 |
Eclipse Short-Cuts (0) | 2010.02.05 |
댓글