Algorithm Study

[Java Algorithm] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค Lv.0 _ ํ™€์ง ๊ตฌ๋ถ„ํ•˜๊ธฐ

microsaurs 2024. 2. 29. 09:42
๐Ÿ‘ฟ ๋ฌธ์ œ ๐Ÿ‘ฟ
์ž์—ฐ์ˆ˜ n ์ด ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์กŒ์„ ๋•Œ ๋งŒ์•ฝ n ์ด ์ง์ˆ˜์ด๋ฉด "n is even" ์„, ํ™€์ˆ˜์ด๋ฉด "n is odd" ๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•ด๋ณด์„ธ์š”.

 

[Algorithm]

โžก๏ธ 2๋กœ ๋‚˜๋ˆด์„ ๋•Œ, ๋‚˜๋จธ์ง€์˜ ์œ ๋ฌด๋ฅผ ์ด์šฉํ•ด ํ™€์ˆ˜ ์ง์ˆ˜๋ฅผ ๊ตฌ๋ถ„

* ๋กœ์ง ํ‘œํ˜„ ๋ฐฉ๋ฒ•

1. if ๋ฌธ
    - System.out.println

    - System.out.printf)

2. ์‚ผํ•ญ์—ฐ์‚ฐ์ž

 

[Code]

import java.util.Scanner;

// 1. if๋ฌธ 
public class Solution1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        
        if ( n % 2 == 0 ) {
            System.out.println(n + " is even");
        } else {
            System.out.println(n + " is odd");
        }
    }
}

// 2. ์‚ผํ•ญ์—ฐ์‚ฐ์ž
public class Solution2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        
        System.out.println(n + " is" + (n % 2 == 0 ? "even" : "odd"));
    }
}

// 3. System.out.printf ์‚ฌ์šฉ
public class Solution3 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        
        if ( n % 2 == 0 ) {
            System.out.printf("%d is even", n);
        } else {
            System.out.println("%d is odd", n);
        }
    }
}

 

[+ Plus]

โญ๏ธ Java์˜ ์ถœ๋ ฅ๋ฌธ 
1. System.out.println()
โžก๏ธ ๊ด„ํ˜ธ ์•ˆ์˜ ๊ฐ’์„ ๊ทธ๋Œ€๋กœ ์ถœ๋ ฅ + ๋งˆ์ง€๋ง‰์— ์ค„๋ฐ”๊ฟˆ์„ ๋„ฃ์–ด์ฃผ๋Š” ๋ฉ”์†Œ๋“œ
2. System.out.printf()
โžก๏ธ ์„œ์‹๋ฌธ์ž์—ด์„ ์‚ฌ์šฉํ•˜์—ฌ ์ถœ๋ ฅ
printf("์„œ์‹๋ฌธ์ž์—ด", value) ํ˜•์‹์œผ๋กœ ์‚ฌ์šฉ

 

* ์„œ์‹๋ฌธ์ž
- %d : ์ •์ˆ˜    - %f : ์‹ค์ˆ˜     - %s : ๋ฌธ์ž์—ด     - %c : ๋ฌธ์ž