더하기 사이클
문제 정보
- 사이트 : 백준 알고리즘 사이트
- 문제 번호 : 1110
- 문제 분류 : for 문
- 난이도 : bronze 1
문제 풀이
내가 짠 코드
- 숫자의 앞자리 : 정수 / 10 이고 숫자의 뒷자리 : 정수 % 10 인것을 이용하여 풀었다.
public class BoJ1110 {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
int bNum = input / 10, aNum = input % 10;
int count = 1;
int temp1 = aNum, temp2 = (bNum + aNum) % 10;
while (!(temp1 == bNum && temp2 == aNum)) {
count++;
int sum = (temp1 + temp2) % 10;
temp1 = temp2;
temp2 = sum;
}
System.out.println(count);
}
}
- BufferedReader와 String으로 다룬 경우 메모리와 시간이 더 짧았다.
public class BoJ1110 {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] input = br.readLine().split("");
String bNum, aNum;
String temp1, temp2;
int count = 1;
if(input.length==1){
bNum = "0";
aNum = input[0];
}else {
bNum = input[0];
aNum = input[1];
}
temp1 = aNum;
temp2 = String.valueOf((Integer.parseInt(bNum) + Integer.parseInt(aNum)) % 10);
while(!(temp1.equals(bNum) && temp2.equals(aNum))){
count++;
String temp = String.valueOf((Integer.parseInt(temp1) + Integer.parseInt(temp2)) % 10);
temp1 = temp2;
temp2 = temp;
}
System.out.println(count);
br.close();
}
문제 출처
썸네일 출처
Image by storyset on Freepik