# BigDecimal의 선언

BigDecimal bigNumber = new BigDecimal("10000.12345");

BigDecimal java.math안에 있으며 위와 같이 선언하시면 됩니다. 특이한 점은 BigDecimal을 초기화하기 위해서는 문

자열을 인자 값으로 넘겨주어야 한다는 점입니다. BigDecimal문자열로 되어 있기 때문입니다.

 

 

# BigDecimal의 사측연산

BigDecimal bigNumber1 = new BigDecimal("100000.12345");
BigDecimal bigNumber2 = new BigDecimal("10000");
						
System.out.println("덧셈(+) :" +bigNumber1.add(bigNumber2));			 // 덧셈(+) :110000.12345
System.out.println("뺄셈(-) :" +bigNumber1.subtract(bigNumber2));		 // 뺄셈(-) :90000.12345
System.out.println("곱셈(*) :" +bigNumber1.multiply(bigNumber2));		 // 곱셈(*) :1000001234.50000
System.out.println("나눗셈(/) :" +bigNumber1.divide(bigNumber2));		// 나눗셈(/) :10.000012345
System.out.println("나머지(%) :" +bigNumber1.remainder(bigNumber2));	// 나머지(%) :0.12345	

 

# BigDecimal의 두 수 비교

BigDecimal bigNumber_down = new BigDecimal("100000.12345");
BigDecimal bigNumber_up = new BigDecimal("1000000.6789");
				
//두 수 비교 compareTo
int compare = bigNumber_down.compareTo(bigNumber_up);
System.out.println(compare);
더보기

-. 같다면                      : 0

-. compartTo(param) 

           param이 크면    : -1

           param이 작으면 : 1

 

programmers.co.kr/learn/courses/30/lessons/43162

 

코딩테스트 연습 - 네트워크

네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있

programmers.co.kr

DFS 와 BFS 두 가지로 문제를 해결해 봤다.

 

BFS

package eun;

import java.util.*;

public class Solution {
	public static void main(String[] args) {
		int[][] computers  = {{1, 1, 0}, {1, 1, 0}, {0, 0, 1}};
		int n = 3;
		solution(n, computers);
	}
	
	public static int solution(int n, int[][] computers) {
		int answer = 0;
		Queue<Integer> q = new LinkedList<>();
		boolean[] visited = new boolean[n];
		
		// 시작점 for 문
		for (int i=0; i<n; i++) {
			if (!visited[i]) {
				q.add(i);
				
				while(!q.isEmpty()) {
					int cur = q.poll();
					visited[cur] = true;
					
					// 시작점에서 갈 수 있는곳 탐색
					for (int j=0; j<n; j++) {
						if(!visited[j] && computers[cur][j] == 1) q.add(j);
					}
				}
				
				answer++;
			}
		}
		System.out.println(answer);
		return answer;
    }
}

 

DFS

package eun;

public class Eun {
	public static int answer =0;
	public static int[] dx = { 0, 1, 0, -1 };
	public static int[] dy = { 1, 0, -1, 0 };
	public static void main(String[] args) {
		int[][] computers  = {{1, 1, 0}, {1, 1, 0}, {0, 0, 1}};
		//int[][] computers  = {{1, 1, 0}, {1, 1, 1}, {0, 1, 1}};
		int n = 3;
		
		solution(n, computers);
	}
	
	public static int solution(int n, int[][] computers) {
		
        for(int y=0; y<n; y++) {
        	for(int x=0; x<n; x++) {
        		if(computers[y][x] == 1) {
        			dfs(x, y, computers, n);
        			answer++;
        		}
        	}
        }
        System.out.println(answer);
		return answer;
    }
	
	public static void dfs(int x, int y, int[][] computers, int n) {
		computers[y][x] = 0;
		
		for (int i=0; i<4; i++) {
			int nx = x + dx[i];
			int ny = y + dy[i];
			
			if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;
			if (computers[ny][nx] == 0) continue;
			dfs(nx, ny, computers, n);
		}
	}
	
}

 

'Algorithm > solution' 카테고리의 다른 글

[프로그래머스 #level2] 조이스틱.java  (0) 2021.02.23
[HASH] 완주하지 못한 선수  (0) 2019.11.02
#2178. 미로탐색  (0) 2018.12.24
#14503. 로봇 청소기  (1) 2018.01.22
#14891. 톱니바퀴  (0) 2018.01.17

programmers.co.kr/learn/courses/30/lessons/42839

 

코딩테스트 연습 - 소수 찾기

한자리 숫자가 적힌 종이 조각이 흩어져있습니다. 흩어진 종이 조각을 붙여 소수를 몇 개 만들 수 있는지 알아내려 합니다. 각 종이 조각에 적힌 숫자가 적힌 문자열 numbers가 주어졌을 때, 종이

programmers.co.kr

완전탐색

 

모든 경우의 수 를 다 따져봐야 하는 문제이다.

 

크게 2가지 스텝으로 나눴다.

    STEP 1) 조합으로 모든 경우의 수 완전 탐색

    STEP 2) 소수 인지 판별

 

1단계에서 중복된 숫자가 나올 수 있는 경우를 제외해 줘야 한다.

    -. 중복 제거를 위해 SET 자료 구조 활용.

    -. 맨 앞이 0인 경우는 제외!

package eun;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;

public class Eun {
	private static int count;
	private static TreeSet<String> ts = new TreeSet<>();
	
	public static void main(String[] args) {
		String numbers = "011";
		
		System.out.println(solution(numbers));
	}
	
	private static int solution(String numbers) {
		List<Character> origin = new ArrayList<>();
		List<Character> result = new ArrayList<>();
		int n = numbers.length();
		
		for (int i=0; i<n; i++) {
			origin.add(numbers.charAt(i));
		}
		
		for (int i=1; i<=n; i++) {
			recursion(origin, result, n, i);			
		}
		
		int answer = count;
		return answer;
	}
	
	private static void recursion(List<Character> origin, List<Character> result, int n, int pick) {
		// 탈출
		if (pick == 0) {
			// 0으로 시작하는거 제거
			if (result.get(0) == '0') return;
				
			// result에 담긴 결과 String화
			String strResult = "";
			for (char c : result) {
				strResult += c;
			}
			
			// 중복 되지 않으면
			if( !ts.contains(strResult) ) {
				// 결과에 추가하고
				ts.add(strResult);
				
				// 소수 판별
				if ( isPrime(Integer.parseInt(strResult)) ) {
					System.out.println(strResult);
					count++;
				}
			}
			
		}
		
		for (int i=0; i<n; i++) {
			result.add(origin.remove(i));
			recursion(origin, result, n-1, pick-1);
			origin.add(i, result.remove(result.size() -1));
		}
	}
	
	
	// 소수 판별
	private static boolean isPrime(int n) {
		int sqrt = (int) Math.sqrt(n);
		
		// 2는 소수
		if (n == 2) return true;
		
		// 1 또는 짝수는 소수가 아님
		if (n == 1 || n%2 == 0) return false;
		
		// 제곱근까지만 홀수로 나눠보면 됨
		for (int i=3; i<=sqrt; i +=2) {
			if ( n%i ==0 ) return false;
		}
		
		return true;
	}
}

+ Recent posts