2015. 3. 8. 02:05
DigitGroupAsInt.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
package digitGroup;
 
import java.util.Stack;
 
/**
 * 10진수를 입력받아, 천(1000)자리 구분자를 추가하는 프로그램.
 * (숫자 타입 처리 및 수행 시간 측정)
 */
public class DigitGroupAsInt {
 
    public static void main(String args[]) {
        int loopCount = 1000000;
        for(int idx=0; idx<10; idx++) {
            long startMilliTime = System.currentTimeMillis();
            benchmark(10, 10, loopCount);
            long endMilliTime = System.currentTimeMillis();
            System.out.println( loopCount + ";" + (endMilliTime - startMilliTime));
            loopCount += 1000000;
        }
    }
     
    private static void benchmark(int startNum, int interval, int loopCount) {
        int inputNumber = startNum;
        for(int cnt=0; cnt<loopCount; cnt++) {
            convert(inputNumber);
            inputNumber += interval;
        }
    }
 
    private static String convert(int number) {
        final int DECIMAL_NUMBER = 10;
        final char THOUSANDS_SEPARATOR = ',';
 
        Stack<Character> digitStack = new Stack<Character>();
        StringBuilder sb = new StringBuilder();
 
        int quotient, spare, count = 0;
        do {
            // 몫과 나머지 계산
            quotient = number / DECIMAL_NUMBER;
            spare = number % DECIMAL_NUMBER;
 
            // 몫을 n 에 재할당, 나머지는 스택에 추가
            number = quotient;
            digitStack.push(Character.forDigit(spare, 10));
 
            // 3개의 숫자를 추가했다면, 구분자를 버퍼에 추가
            if (++count == 3 && quotient > 0) {
                digitStack.push(THOUSANDS_SEPARATOR);
                count = 0;
            }
 
        } while (quotient > 0);
 
        // 스택에 저장된 숫자를 꺼내 문자열 버퍼에 추가
        while (!digitStack.empty()) {
            sb.append(digitStack.pop());
        }
 
        return sb.toString();
    }
 
}
Posted by 곽중선