1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
 
public class Main {
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        int n = Integer.parseInt(br.readLine());
        String str = null;
        int[][] numArr = new int[n][];
        String[] temp = new String[n];
        
        //receives inputs and saves into temp as string
        int esc = 0;
        while((str = br.readLine()) != null) {
            temp[esc] = str;
            esc++;
            if(esc == n) break;
        }
        //converts string to two-dimesional array int
        for(int i = 0; i < n; i++) {
            StringTokenizer st = new StringTokenizer(temp[i]);
            esc = st.countTokens();
            
            int j = 0;
            numArr[i] = new int[st.countTokens()];
            while(st.hasMoreTokens()) {
                numArr[i][j] = Integer.parseInt(st.nextToken());
                j++;
            }
        }
        
        //find avg, compare and print out  
        for(int i = 0; i < numArr.length; i++) {
            double avg = 0;
            for(int z = 1; z < numArr[i].length; z++) {
                avg += numArr[i][z]; 
            }
            
            avg /= (numArr[i].length - 1);
            int count = 0;
            for(int z = 1; z < numArr[i].length; z++) {
                if(avg < numArr[i][z]) count++;
            }
            avg = (double)count / (numArr[i].length - 1* 100;
            bw.write(String.format("%.3f", avg) + "%\n");
        }
        bw.flush();
        bw.close();
        br.close();
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

알고리즘을 접근할 때 사용자의 입력값을 당연히 저장해야 되는 줄 알았는데 생각해보니 bufferedwriter의 장점이 flush로 나중에 한 번에 처리가 가능하다는 점을 사용을 못 했네요.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
 
 
public class Main{
    public static void main(String args[]) throws NumberFormatException, IOException{
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        int count = Integer.parseInt(br.readLine());
        
        for(int i = 0 ; i < count ; i ++){
            String datas [] = br.readLine().split(" ");
            double sum = 0;
            double avg = 0;
            double tempCnt = 0;
            
            for(int j = 1 ; j < datas.length ; j ++){
                sum += Double.parseDouble(datas[j]);
            }
            avg = (sum / (datas.length -1) );
            
            for(int j = 1 ; j < datas.length ; j ++){
                if(Double.parseDouble(datas[j]) > avg){
                    tempCnt++;
                }
            }
            
            bw.write( String.format("%.3f", (tempCnt / (datas.length -1)) * 100)+"%");
            bw.newLine();
        }
        
        bw.flush();
        bw.close();
        br.close();
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

여기처럼 값을 받자마자 바로 처리하고 값을 다시 받는 식으로 하면 제 코드처럼 굳이 2차원 배열에 안 담고 계산하면 되니

오늘도 배워갑니다!

'알고리즘' 카테고리의 다른 글

백준 6단계(4673)  (0) 2019.12.07
백준 6단계(15596)  (0) 2019.12.07
백준 5단계(8958)  (0) 2019.11.28
백준 5단계(1546)  (0) 2019.11.28
백준 5단계(3052)  (0) 2019.11.28
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 
public class Main {
    
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        int n = Integer.parseInt(br.readLine());
        int max = 0;
        String[] strArr = new String[n];
        for(int i = 0; i < n; i++) {
            strArr[i] = br.readLine();
        }
        
        int[] totalArr = new int[n];
        for(int i = 0; i < n; i++) {
            int count = 0;
            for(int j = 0; j < strArr[i].length(); j++) {
                if(strArr[i].charAt(j) == 'X') count = 0;
                else count++;
                totalArr[i] += count;
            }
            bw.write(String.valueOf(totalArr[i]) + "\n");
        }
        bw.flush();
        
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

'알고리즘' 카테고리의 다른 글

백준 6단계(15596)  (0) 2019.12.07
백준 5단계(4344)  (0) 2019.11.28
백준 5단계(1546)  (0) 2019.11.28
백준 5단계(3052)  (0) 2019.11.28
백준 5단계(2577)  (0) 2019.11.28
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
 
 
public class Main {
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        //receives input and divides by stringtokeinzer
        int n = Integer.parseInt(br.readLine());
        double[] arr = new double[n];
        String str = br.readLine();
        StringTokenizer st = new StringTokenizer(str);
        
        //max for finding the highest number
        double max = 0;
        int t = 0;
        
        while(st.hasMoreTokens()) {
            arr[t] = Integer.parseInt(st.nextToken());
            if(max < arr[t]) max = arr[t];
            t++;
        }
        
        //doulbe is used for avg, followed the given equation to solve
        double avg = 0;
        t = 0;
        for(; t < arr.length; t++) {
            arr[t] = (arr[t]/ max) * 100;
            avg += arr[t];
        }
        avg /= n;
        bw.write(String.valueOf(avg));
        bw.flush();
        
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

'알고리즘' 카테고리의 다른 글

백준 5단계(4344)  (0) 2019.11.28
백준 5단계(8958)  (0) 2019.11.28
백준 5단계(3052)  (0) 2019.11.28
백준 5단계(2577)  (0) 2019.11.28
백준 5단계(2920)  (0) 2019.11.28
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
 
public class Main {
    
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        //reads all the input strings and converts into int 
        int r = 0;
        String str = null;
        int[] numArr = new int[10];
        while((str = br.readLine()) != null) {
            numArr[r] = Integer.parseInt(str);
            r++;
            if(r == 10break;
        }
        
        //if checkarr index is remainder of 42 equal to 0, add 1 itself and increase r 
        r = 0;
        int[] checkArr = new int[1000];
        for(int i = 0; i < numArr.length; i++) {
            if(checkArr[numArr[i] % 42== 0) {
                checkArr[numArr[i] % 42]++;
                r++;
            }
        }
        
        bw.write(String.valueOf(r));
        bw.flush();
        
        
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

'알고리즘' 카테고리의 다른 글

백준 5단계(8958)  (0) 2019.11.28
백준 5단계(1546)  (0) 2019.11.28
백준 5단계(2577)  (0) 2019.11.28
백준 5단계(2920)  (0) 2019.11.28
코테 11/25/19  (0) 2019.11.25
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
 
 
public class Main {
    
    public static int[] result(int n) {
        //String is used to find out multiplied number's length
        String temp = Integer.toString(n);
        int[] beforeResult = new int[temp.length()];
        int[] afterResult = new int[10];
        
        //start putting parameter n's one's value 
        for(int i = 0; i < beforeResult.length; i++) {
            beforeResult[i] = n % 10;
            n /= 10;
        }
        
        //++ on afterResult, index of beforeResult index i value
        for(int i = 0; i < beforeResult.length; i++) {
            afterResult[beforeResult[i]]++;
        }
        
        //or
//        for(int i = 0; i < beforeResult.length; i++) {
//            afterResult[n % 10]++;
//            n /= 10;
//        }
        
        //returns the array 
        return afterResult;
    }
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        //receiving value and converting to int 
        String str = null;
        int[] arr = new int[3];
        int n = 0;
        while((str = br.readLine()) != null) {
            arr[n] = Integer.parseInt(str);
            n++;
            if(n == 3break;
        }
        
        //setting n to 1 for reuse as multiply result from inputted number
        n = 1;
        for(int i = 0; i < arr.length; i++) {
            n *= arr[i];
        }
        
        //result method brings result
        int[] arr2 = result(n);
        
        //prints out how many times the number has been used
        for(int i = 0; i < arr2.length; i++) {
            bw.write(arr2[i] + "\n");
        }
        bw.flush();
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

'알고리즘' 카테고리의 다른 글

백준 5단계(1546)  (0) 2019.11.28
백준 5단계(3052)  (0) 2019.11.28
백준 5단계(2920)  (0) 2019.11.28
코테 11/25/19  (0) 2019.11.25
기초 알고리즘(38번 치킨쿠폰 재귀)  (0) 2019.11.24
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
 
public class Main {
    
    public static String check(int[] numArr) {
        String str = "mixed";
        boolean asc = true;
        boolean desc = true;
        for(int i = 1; i <= numArr.length; i++) {
            if(numArr[i - 1!= i) asc = false;
            if(numArr[i - 1!= numArr.length - i + 1) desc = false;
        }
        if(asc) str = "ascending";
        if(desc) str = "descending";
        return str;
    }
    
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        String input = br.readLine();
        StringTokenizer st = new StringTokenizer(input);
        
        int size = st.countTokens();
        int[] numArr = new int[size];
        
        for(int i = 0; i < size; i++) {
            numArr[i] = Integer.parseInt(st.nextToken());
        }
        bw.write(check(numArr));
        bw.flush();
    }
    public static String check2(int[] input) {
        String result = "mixed";
        int[] ascending = new int[input.length];
        int[] descending = new int[input.length];
        for(int i = 0; i < input.length; i++) {
            ascending[i] = i + 1;
            descending[i] = input.length - i;
        }
        boolean asc = true;
        boolean desc = true;
        for(int i = 0; i < input.length; i ++) {
            if(ascending[i] != input[i]) asc = false;
            if(descending[i] != input[i]) desc = false;
        }
        if(asc) result = "ascending";
        else if(desc) result = "descending";
        return result;
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

'알고리즘' 카테고리의 다른 글

백준 5단계(3052)  (0) 2019.11.28
백준 5단계(2577)  (0) 2019.11.28
코테 11/25/19  (0) 2019.11.25
기초 알고리즘(38번 치킨쿠폰 재귀)  (0) 2019.11.24
백준 5단계(2562)  (0) 2019.11.24

요새 계속 코테만 보는 것 같은 느낌적인 느낌..

1. 피포나치 재귀 호출로 구해보기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package algo.codingtests.kongstudios;
 
import java.util.Scanner;
 
public class Fibonacci {
 
    public static int fibo(int number) {
        
        if(number == 0return 0;
        if(number == 1return 1;
        return fibo(number - 1+ fibo(number - 2);
    }
    
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int number = scan.nextInt();
        System.out.println(fibo(number));
    }
    
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

2. 스트링 순서 바꾸기 version 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package algo.codingtests.kongstudios;
 
import java.util.Scanner;
 
public class PartialWordReverse {
    
    public static void printWords(String str) {
        
        int i = 0;
        for(; i < str.length() && str.charAt(i) != ' '; i++) {
            System.out.print(str.charAt(i));
        }
        
        String words = "";
        for(; i < str.length(); i++) {
            if(str.charAt(i) != ' ') {
                words += str.charAt(i);
            } else {
                System.out.print(new StringBuilder(words).reverse().toString() + " ");
                words = "";
                
            }
            
        }
        
        System.out.print(words);
    }
    
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String str = scan.nextLine();
        System.out.println(str);
        System.out.println(new StringBuilder(str).reverse().toString());
        System.out.println("=============");
        
        printWords(str);
        
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 version1 에서는 앞 단어와 그리고 맨 뒤 단어는 정상적으로 출력이되고 중간 단어들은 순서를 바꿔서 출력하기

 

version2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package algo.codingtests.kongstudios;
 
import java.util.Scanner;
 
public class PartialWordReverseVowl {
    
    public static boolean isVowel(char c) {
        return (c == 'a' || c == 'A' || c == 'e'
                || c == 'E' || c == 'i' || c == 'I'
                || c == 'o' || c == 'O' || c == 'u'
                || c == 'U');
    }
    
    public static String partialWorrdReverse(String str) {
        int i = 0
        int j = str.length() - 1
        char[] str1 = str.toCharArray(); 
        while (i < j) { 
            if (!isVowel(str1[i])){ 
                i++
                continue
            } 
            if (!isVowel(str1[j])){ 
                j--
                continue
            } 
      
            char temp = str1[i]; 
            str1[i]= str1[j]; 
            str1[j]= temp; 
      
            i++
            j--
        } 
       ; 
        return String.valueOf(str1); 
    }
    
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String str = scan.nextLine();
        System.out.println(partialWorrdReverse(str));
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

버젼2에서는 모음만 비교해서 바꿔주기

 

3. Stack를 사용해서 Queue방식 출력

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package algo.codingtests.kongstudios;
 
 
public class QueueSolution {
 
    private Stack<Integer> s1 = new Stack<>();
    private Stack<Integer> s2 = new Stack<>();
    int front = 0;
 
    // Push element x to the back of queue.
    public void push(int x) {
        if (s1.empty())
            front = x;
        s1.push(x);
    }
    
    public void pop() {
        if (s2.isEmpty()) {
            while (!s1.isEmpty())
                s2.push(s1.pop());
        }
        s2.pop();    
    }
    
    public boolean empty() {
        return s1.isEmpty() && s2.isEmpty();
    }
    
    public int peek() {
        if (!s2.isEmpty()) {
                return s2.peek();
        }
        return front;
    }
    public static void main(String[] args) {
        QueueSolution solution = new QueueSolution();
        solution.push(1);
        solution.push(2);
        solution.push(3);
        solution.push(4);
        solution.push(5);
        
        System.out.println(solution.peek());
    
        
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

stack은 lifo 방식이기때문에 push했을때 원래는 5 4 3 2 1순서되로 출력이되야하지만 

push, pull, peek, empty의 조건들을 바꿔서 1이먼저 출력!

 

4. Implementing queue using stack

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package algo.codingtests.kongstudios;
 
 
public class QueueUsingStack {
 
    public static void main(String[] args) {
        QueueStack qs = new QueueStack();
        qs.stack1 = new Stack<Integer>();
        qs.stack2 = new Stack<Integer>();
        qs.enQueue(qs, 1);
        qs.enQueue(qs, 2);
        qs.enQueue(qs, 3);
        
        System.out.println(qs.deQueue(qs));
        System.out.println(qs.deQueue(qs));
        System.out.println(qs.deQueue(qs));
        
        System.out.println("=================");
        System.out.println("using queue example");
        Queue<Integer> q = new LinkedList<>();
        for(int i = 0; i < 5; i++) {
            q.add(i);
        }
        
        for(Integer e : q) {
            System.out.println(e);
        }
        
        q.remove();
        System.out.println(q.peek());
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package algo.codingtests.kongstudios;
 
 
public class QueueStack {
 
    Stack<Integer> stack1;
    Stack<Integer> stack2;
    
    public void push(Stack<Integer> qs, int n) {
        qs.push(n);
    }
    
    public int pop(Stack<Integer> qs) {
        if(qs.isEmpty()) {
            System.out.println("Nothing is in");
            System.exit(0);
        }
        int x = qs.pop();
        return x;
    }
    public void enQueue(QueueStack qs, int n) {
        push(qs.stack1, n);
    }
    
    public int deQueue(QueueStack qs) {
        int x = 0;
        
        if(qs.stack1.isEmpty() && qs.stack2.isEmpty()) {
            System.out.println("queue is empty");
            System.exit(0);
        }
        if(qs.stack2.isEmpty()) {
            while(!qs.stack1.isEmpty()) {
                x = pop(qs.stack1);
                push(qs.stack2, x);
            }
        }
        x = pop(qs.stack2);
        return x;
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

queue의 enqueue 랑 dequeue사용

솔직히 이해는 조금 부족함

 

5. Two Sum Method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package algo.codingtests.kongstudios;
 
import java.util.Scanner;
 
public class TwoSumMethods {
 
    public static int[] bruteForce(int[] numbers, int target) {
 
        for (int i = 0; i < numbers.length; i++) {
            for (int j = 0; j < numbers.length; j++) {
                if (numbers[i] + numbers[j] == target) {
                    return new int[] { i, j };
                }
            }
        }
        return new int[] {};
    }
 
    public static int[] sortedMethod(int[] numbers, int target) {
        
        Arrays.sort(numbers);
        int left = 0;
        int right = numbers.length - 1;
        while(left < right) {
            System.out.println(numbers[left] + numbers[right]);
            if(numbers[left] + numbers[right] == target) {
                return new int[] {left, right};
            } else if(numbers[left] + numbers[right] < target) {
                left++;
                System.out.println("left +");
            } else {
                right--;
                System.out.println("right -");
            }
        }
        return new int[] {};
    }
 
    public static int[] hashMethod(int[] numbers, int target) {
        Map<Integer, Integer> numMap = new HashMap<>();
        for(int i = 0; i < numbers.length; i++) {
            int complement = target - numbers[i];
            if(numMap.containsKey(complement)) {
                return new int[] {numMap.get(complement), i};
            } else {
                numMap.put(numbers[i], i);
            }
        }
        return new int[] {};
    }
    
//    public static Vector<Integer> twoSum(Vector<Integer> nums, int target) {
//        Vector<Integer> vec = new Vector<Integer>(100);
//        for(Integer e : nums) {
//            System.out.println(e);
//        }
//        for(int i = 0; i < nums.size(); i++) {
//            int complement = target - nums.get(i);
//            if(vec.contains(complement)) {
//                Vector<Integer> vecs = new Vector<Integer>();
//                vecs.add(0, vec.get(complement));
//                vecs.add(1, i);
//                return vecs;
//            } else {
//                vec.add(nums.get(i), i);
//            }
//        }
//        return new Vector<Integer>();
//    }
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        
        int[] numbers = new int[n];
        for (int i = 0; i < n; i++) {
            numbers[i] = scan.nextInt();
        }
//        Vector<Integer> numbers = new Vector<Integer>();
//        for (int i = 0; i < n; i++) {
//            numbers.add(i, scan.nextInt());
//        }
        int target = scan.nextInt();
//        twoSum(numbers, target);
//        System.out.println("asdfasdfsd");
//        for(Integer e : twoSum(numbers, target)) {
//            System.out.println(e);
//        }
//
        int[] result = hashMethod(numbers, target);
 
        
        if (result.length == 2) {
            System.out.println(result[0+ "    " + result[1]);
        } else {
            System.out.println("found no results");
        }
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

6. Happy Number

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package algo.codingtests.kongstudios;
 
import java.util.Scanner;
 
public class HappyNumber {
 
    public static int checkSquare(int n) {
        int squareNum = 0;
        while(n != 0) {
            squareNum += (n % 10* (n % 10);
            n /= 10;
        } 
        return squareNum;
    }
    
    public static boolean isHappyNumber(int n) {
        Set<Integer> st = new HashSet<Integer>();
        System.out.println("number before is " + n);
        while(st.add(n)) {
//            n = checkSquare(n);
            int squareNum = 0;
            while(n != 0) {
                squareNum += (n % 10* (n % 10);
                n /= 10;
            } 
            n = squareNum;
            System.out.println("after check is " + n);
        }
        return (n == 1);
    }
    
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        System.out.println(isHappyNumber(n) ? "happy":"not happy");
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

 

코테 하면서 오늘 새로운것들 많이 배웠다

stack queue사용법, happy number algo, two sum algo 그리고 string reverse조건으로 결정하기 

'알고리즘' 카테고리의 다른 글

백준 5단계(2577)  (0) 2019.11.28
백준 5단계(2920)  (0) 2019.11.28
기초 알고리즘(38번 치킨쿠폰 재귀)  (0) 2019.11.24
백준 5단계(2562)  (0) 2019.11.24
백준 5단계(10818)  (0) 2019.11.23

영상 버젼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package algo.youtube.a38;
 
import java.util.Scanner;
 
public class Main {
    
    public static void doFunc(int coupon, int stamp, int k, int ans) {
        if(coupon > 0) {
            coupon--;
            stamp++;
            ans++;
            doFunc(coupon, stamp, k, ans);
            return;
        } else if(stamp > 0) {
            if(stamp/> 0) {
                stamp -= k;
                coupon++;
                doFunc(coupon, stamp, k, ans);
            }
        }
        if(coupon == 0 && stamp/== 0) {
            System.out.println(ans);
        }
    }
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        
        for(int i = 0; i < 3; i++) {
            int n = scan.nextInt();
            int k = scan.nextInt();
            int coupon = n;
            doFunc(coupon, 0, k, 0);
        }
        
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

제 제귀 버젼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package algo.youtube.a38;
 
 
public class TaewonMain {
    
    public static int couponAmount(int chicken, int coupon) {
        int couponNum = chicken/coupon;
        int temp = 0;
        if(couponNum >= coupon) {
            temp = couponAmount(couponNum, coupon);
            
        }
        return  couponNum  + temp;
    }
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        int[] list = new int[2];
        for(int i = 0; i < 3; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            list[0= Integer.parseInt(st.nextToken());
            list[1= Integer.parseInt(st.nextToken());
            int couponResult = couponAmount(list[0], list[1]);
            bw.write(list[0+ couponResult + "\n");
        }
        bw.flush();
        bw.close();
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

저는 쿠폰의 계수만 재귀로 구했는데 영상에서는 값도 같이 구했습니다. 같이 구하는걸 구현할려고 3시간동안 고민한 저한테는 쿠폰 계수만이라도 재귀로 얻을 수 있어서 만족합니다...

 

이것도 백준문제인데 제출하면 틀렸다고 뜨는데 재귀호출때문에 그런건지 아니면 안보이는 오류가 있는 것 같네요

'알고리즘' 카테고리의 다른 글

백준 5단계(2920)  (0) 2019.11.28
코테 11/25/19  (0) 2019.11.25
백준 5단계(2562)  (0) 2019.11.24
백준 5단계(10818)  (0) 2019.11.23
백준 4단계(11/23/19)(10952, 10951, 1110)  (0) 2019.11.23

+ Recent posts