•  코드

초기 코드 1 : 각 숫자의 자리수를 Math.log10(i)+1를 통해 구한다. 결과는 시간초과

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
	
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());
        int count = 0;
        
        for(int i=1;i<=N;i++) 
        	count += Math.log10(i)+1;
        
        System.out.println(count);  
	}
}

 

 

초기 코드 2 :  String으로 반복문이 돌때마다 +i를 해준 뒤 string의 길이를 length()로 출력해보았다.

                  결과는 메모리초과

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
	
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());
        String count = "";
        
        for(int i=1;i<=N;i++) 
        	count += i;
        
        System.out.println(count.length());  
	}
}

 

  • 맞은 코드

일단 i의 수 120을 입력했다는 가정으로 보면

1의 자리이상 120개 + 2의 자리이상 120-9(1의 자리)개 + 3의 자리이상 120-9-90(2의 자리)개로 더 해주는 방식으로 풀었다.

결과는 맞았습니다!!

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
	
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());
        int count = 0;
        
        for(int i=1;i<=N;i*=10) 
        	count += N - (i-1);
        
        System.out.println(count);  
	}
}

 

+ Recent posts