반응형
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;
}
}
출처 |
반응형
'알고리즘 > JAVA' 카테고리의 다른 글
[JAVA] 백준 알고리즘 2583 : 영역 구하기 (0) | 2018.09.19 |
---|---|
[JAVA] 백준 알고리즘 10825 : 국영수 (0) | 2018.09.18 |
[JAVA] 백준 알고리즘 2294 : 동전 2 (DP) (0) | 2018.09.14 |
[JAVA] 백준 알고리즘 2667 : 단지번호붙이기 (BFS) (0) | 2018.09.13 |
[JAVA] 백준 알고리즘 1697 : 숨바꼭질 (BFS) (0) | 2018.09.13 |