Notice
Recent Posts
Recent Comments
Link
«   2025/12   »
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
Tags more
Archives
Today
Total
관리 메뉴

jeongwon

[백준JAVA] 1110번 - 더하기 사이클 본문

오늘의 문제

[백준JAVA] 1110번 - 더하기 사이클

jeongwon_ 2022. 5. 24. 21:02

나의 답안: (시간초과)

package back;

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

class Main{
	public static void main(String[] args) throws IOException   {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));	
		int n=Integer.parseInt(bf.readLine());
		bf.close();
		
		int count=0;
		int a = 0;
		
		while(n!=a) {
			count++;
			a = ((n%10)*10) + ((n/10+n%10)%10);			
		}
		System.out.println(count);
	}	
}

 

 

답안2 :(시간초과)

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

class Main{
	public static void main(String[] args) throws IOException   {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));	
		int n=Integer.parseInt(bf.readLine());
		bf.close();
		
		int count=0;
		int a = n;
		int b = 0;
		
		while(a!=b) {
			count++;
			b = ((n%10)*10) + ((n/10+n%10)%10);			
		}
		System.out.println(count);
	}	
}

bf.readLine() 이 while의 조건식에서 반복 호출되지 않도록 변수에 값을 저장해보았으나 마찬가지였다.

 

개선 답안 : 

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

class Main{
	public static void main(String[] args) throws IOException   {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));	
		int n=Integer.parseInt(bf.readLine());
		bf.close();
		
		int count=0;
		int a = n;
		
		do {
			count++;
			n = ((n%10)*10) + ((n/10+n%10)%10);			
		}while(a!=n);
		System.out.println(count);
	}	
}

b라는 변수를 새로 생성하지 않고, n이라는 변수를 다시 활용했더니 시간초과 문제가 해결되었다.

이 경우 while 문 조건식이 a=n 으로 불발될 것이므로 do~while 문을 적용해야 한다. (혹은 조건문 추가)

 

(main 메소드 호출 시 Stack 영역에 main 메소드 및 main 메소드 내 지역변수가 메모리에 할당되며, main 메소드 종료 시 소멸)

 

참고답안 : https://st-lab.tistory.com/42

 

 


 

 

'오늘의 문제' 카테고리의 다른 글

[백준 JAVA] 2562번 - 최댓값  (0) 2022.05.25
[백준 JAVA] 10818번 - 최소, 최대  (0) 2022.05.25
[백준 JAVA] 10952번 - A+B - 5  (0) 2022.05.24
[백준 JAVA] 10871번 X보다 작은 수  (0) 2022.05.22
[백준 JAVA] 11021번 A+B  (0) 2022.05.19