본문 바로가기

자료구조

기본 알고리즘

세 값의 최댓값

최대값을 구하는 과정

  1. max에 a값을 넣는다.
  2. b값이 max보다 크면 max에 b값을 넣는다.
  3. c값이 max보다 크면 max에 c값을 넣는다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;


public class Main {
	public static void main(String[] args) throws IOException{
		System.out.println(max3(3,2,1));
	}
	static int max3(int a, int b, int c) {
		int max = a;
		if(b > max)
			max = b;
		if (c > max)
			max = c;
		
		return max;
	}
}

세 값의 중앙값

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;


public class Main {
	public static void main(String[] args) throws IOException{
		System.out.println(med3(3,2,1));
	}
	static int med3(int a, int b, int c) {
		if (a >= b)
			if(b >= c)
				return b;
			else if (a <= c)
				return a;
			else
				return c;
		else if (a > c)
			return a;
		else if (b > c)
			return c;
		else
			return b;
	}
}

연산자와 피연산자

  • 단항 연산자 : a++
  • 2항 연산자 : a < b
  • 3항 연산자 : a ? b : c

조건 연산자 ? : 는 자바에서 유일한 3항 연산자입니다.

식 a ? b : c 는 a가 true이면 b를 반환하고 false 이면 c를 반환합니다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;


public class Main {
	public static void main(String[] args) throws IOException{
		int x = 5, y = 19;
		int a = (x > y) ? x : y;
		System.out.println(a);
		System.out.println((x == 0) ? "x=0" : "x != 0");
	}
}

가우스의 덧셈

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;


public class Main {
	public static void main(String[] args) throws IOException{
		int n = 10;
		int sum = (n + 1) * (n / 2) + (n % 2 == 1 ? (n + 1) / 2 : 0);
		System.out.println(sum);
	}
}

드모르간 법칙

각 조건을 부정하고 논리곱을 논리합으로, 논리합을 논리곱으로 바꾸고 다시 전체를 부정하면 원래의 조건과 같다.

  • x && y 와 (!x || !y)는 같습니다.
  • x || y 와 (!x && !y)는 같습니다.
do {
			System.out.println(no);
		} while(no < 10 || no > 99);
int no = 10;
		do {
			System.out.println(no);
		} while(!(no >= 10 && no <= 99));

연속 조건과 종료 조건

'자료구조' 카테고리의 다른 글

정렬  (0) 2021.08.17
재귀 알고리즘  (0) 2021.08.14
스택과 큐  (0) 2021.08.14
검색  (0) 2021.08.13
기본 자료구조  (0) 2021.08.13