본문 바로가기

Algorithm/알고리즘 문제 풀이

알고리즘 (6월 9일)

1. 문제 (코딩도장, 앞뒤가 같은 수)

https://codingdojang.com/scode/398?answer_mode=hide 

 

코딩도장

프로그래밍 문제풀이를 통해서 코딩 실력을 수련

codingdojang.com


2. 생각

숫자 형태의 문자열을 콤마가 포함된 금액 표기식 문자열로 바꾸어주는 프로그램을 작성하시오.

 

※ 단, 프로그래밍 언어에서 지원하는 금액변환 라이브러리는 사용하지 말것

 

ex) 1000 → 1,000,  20000000 20,000,000,  -3245.24 -3,245.24

 

  1. 숫자 형태의 문자열을 입력받는다.
  2. 문자열을 쪼개서 "digits" arraylist에 저장한다.
  3. indexOf 메소드를 이용하여 .가 존재할 경우와 존재하지 않을 경우를 나눠서 생각
  4. .가 존재하지 않을 경우
    digits 리스트에서 하나씩 뽑아서 conversion 리스트에 저장한다. 이때, 하나씩 카운트하면서 카운트 값이 3이 되면 ","를 하나씩 추가해준다.
  5. .가 존재할 경우 
    소수점 자리 숫자는 그대로 복사하고, 일의 자리 이상부터는 .가 존재할 경우와 동일한 과정을 실행한다.
  6.  4~5 단계 과정이 끝나면 arrayList 원소들을 string 타입 변수에 저장한 뒤, 출력한다.

3. 풀이 및 코드 분석

import java.util.Scanner;
import java.util.ArrayList;

public class test {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		ArrayList<String> digits = new ArrayList<>();
		ArrayList<String> conversion = new ArrayList<>();
		
		// 숫자 형태의 문자열을 입력
		System.out.println("숫자를 입력하시오:");
		String inputData = scan.next();
		String convertedNum = "";
		int count=0, result;
		
		// 문자열 분리하여 리스트에 저장
		for(int i=0; i<inputData.length(); i++) {
			digits.add(inputData.substring(i, i+1));
		}
		
		
		int size = digits.size();
		int position = digits.indexOf(".");
		
		// . 가 존재하지 않을 경우
		if(position==-1) {
			for(int i=size-1; i>=0; i--) {
				conversion.add(0, digits.get(i));
				count++;
				
				if((count==3)&&(digits.get(0).equals("-"))&&(i==1)) {
					continue;
				}else if((count==3)&&(i!=0)) {
					conversion.add(0, ",");
					count = 0;
				}
			}
		}else { // . 가 존재할 경우
			
			conversion.add(".");
			
			// 소수점 자리 숫자들은 그대로 
			for(int i=position+1; i<digits.size(); i++) {
				conversion.add(digits.get(i));
			}
			
			for(int i=position-1; i>=0; i--) {
				count++;
				conversion.add(0, digits.get(i));
				
				if((count==3)&&(digits.get(0).equals("-"))&&(i==1)) {
					continue;
				}else if((count==3)&&(i!=0)) {
					conversion.add(0, ",");
					count = 0;
				}
			}			
		}
		
		// 리스트를 숫자 자료형으로 변환
		for(int i=0; i<conversion.size(); i++) {
			convertedNum += conversion.get(i);
		}
		
		// 결과 출력
		System.out.printf("\n금액은 %s원입니다.\n", convertedNum);
	}
}

4. 메모

 

  • ArrayList에서 prepend하는 방법
    → ArrayList.add(0, "(추가 원소)")  :  ArrayList의 0번째 자리에 추가함으로서 리스트에 prepend할 수 있다.

'Algorithm > 알고리즘 문제 풀이' 카테고리의 다른 글

알고리즘 (6월 12일)  (0) 2022.06.12
알고리즘 (6월 10일)  (0) 2022.06.11
알고리즘 (6월 8일)  (0) 2022.06.08
알고리즘 (6월 7일) - (2)  (0) 2022.06.07
알고리즘 (6월 7일)  (0) 2022.06.07