2015. 3. 8. 02:13


DigiGroupAsStr2.java


package digitGroup;

/**
 * 10진수를 입력받아, 천(1000)자리 구분자를 추가하는 프로그램.
 */
public class DigiGroupAsStr2 {

	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 char THOUSANDS_SEPARATOR = ',';

		// 입력 숫자를 문자열 타입으로 변환
		String numberAsStr = String.valueOf(number);
		StringBuilder sb = new StringBuilder(numberAsStr.length() / 3
				+ numberAsStr.length());

		// 맨 앞부분에서 잘라낼 길이를 계산하고, 출력 버퍼에 담는다.
		int firstPos = numberAsStr.length() % 3;
		int charIdx = 0;
		for(; charIdx<firstPos; charIdx++) {
			sb.append(numberAsStr.charAt(charIdx));
		}
		
		int counter = 0;
		for(; charIdx<numberAsStr.length(); charIdx++) {
			if(counter % 3 == 0 && numberAsStr.length() > 3) {
				sb.append(THOUSANDS_SEPARATOR);
			} 
			counter ++;
			sb.append(numberAsStr.charAt(charIdx));
		}

		return sb.toString();
	}

}

Posted by 곽중선