본문 바로가기
with my rubber duck/codingTest

그리디 알고리즘 공부하기 (feat.동빈나 이코테 강의)

by stilinski 2022. 7. 29.
728x90

 

 

https://youtu.be/2zjoKjt97vQ

두번째 연습문제 풀기

 

내가 직접 풀어본 버전

import java.util.Scanner;
public class Main
{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String line = sc.nextLine();
        int result=Integer.parseInt(String.valueOf(line.charAt(0)));
       for(int i =1;i<line.length();i++){
           int num =Integer.parseInt(String.valueOf(line.charAt(i)));
               if(num==0 || result==0){
                   result += num;
               }else{
                   result *= num;
               }
            
       }
       System.out.println(result);
    }
}

 

 

 

답 버전

import java.util.Scanner;
public class Main
{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        //첫번째 문자를 숫자로 변경한 값을 대입.
        //문자 0의 아스키코드 값을 빼주면 숫자가 됨.
        long result=str.charAt(0)-'0';
       for(int i =1;i<str.length();i++){
           int num = str.charAt(i)-'0';
           //0이나 1이면 + 수행
               if(num<=1 || result<=1){ 
                   result += num;
               }else{
                   result *= num;
               }
            
       }
       System.out.println(result);
    }
}

뭔가 내가 푼거랑 로직은 비슷해서 놀람

나도 드디어 뭔가 깨우친것인가..?!

근데 0이아니라 1이어도 곱하기보단 더하기가 숫자 더 크게 할 수 있다느 거 간과함.

그리고 캐릭터에서 integer.parseInt안해도 0아스키코드 값 빼면 숫자 만들 수 있는 첨앎.

728x90

댓글