본문 바로가기

알고리즘/JAVA

[JAVA] 백준 알고리즘 11179 : 2진수 뒤집기 (역치)

반응형


2진수 뒤집기



  문제






  소스1


import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {
	public static int answer;
	static Queue<Integer> st = new LinkedList<Integer>();
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);	
		int N = sc.nextInt();
		int num = 0;
		int result = 0;

		while(N>=1) {
			num++;
			st.add(N%2); // 나머지
			N /= 2;	
		}
		
		while(!st.isEmpty()) {
			num--;
			if (st.poll() == 1) {
				result += Math.pow(2, num);
			}
		}
		
		System.out.println(result); 
	}
}



  소스2


import java.util.Scanner;

public class Main {
	public static int answer;

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);	
		String sr;
		
		answer = 0;
		sr = "";
		int N = sc.nextInt();

		while(N>=1) {
			sr += String.valueOf(N%2); // 나머지
			N /= 2;
		}
		
		answer = reverse(sr);
		System.out.println(answer); 
	
	}
	
	public static int reverse(String str) {
		int result = 0;
		
		for (int i=0; i<=str.length()-1; i++) {
			if (str.charAt(i) == '1')
			{
				result += Math.pow(2, (str.length()-1)-i);
			}
		}

		return result;
	}
}






  출처


https://www.acmicpc.net/problem/11179




반응형