알고리즘 기초 100제 4번

less than 1 minute read

문제소개

  • 10진수를 2진수로 변환하시오.
  • 19
  • 정답 : 10011
public class TestEx {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("10진수를 입력하세요!");

		ArrayList<Integer> tempList = new ArrayList<>();

		int input = sc.nextInt();

		while(input >= 1) {
			if(input % 2 == 0) {
				tempList.add(0,0);	// 배열의 맨 앞에 저장
				input = input / 2 ;

			}else {
				tempList.add(0,1);	// 배열의 맨앞에 저장
				input = input / 2 ;
			}
		}

		for(int number : tempList) {
			System.out.println(number);
		}
	}
}

1.png

List를 활요해서 풀었지만, 의도한 바와 다르게 출력이 되었다.


▶ Solution

public class TestEx {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		int inputNum = sc.nextInt();
		int bin[] = new int[100];

		int i = 0;
		int mok = inputNum;

		while(mok > 0) {
			bin[i] = mok % 2;
			mok /= 2;
		}

		i--;

		for(;  i>=0; i--) {
			System.out.println(bin[i]);
		}
	}
}


📑 출처

Categories:

Updated:

Leave a comment