백준 알고리즘 단계별/while 문
백준 BOJ C# [1110] [더하기 사이클]
재호우96
2020. 1. 15. 22:29
반응형

백준 BOJ C# [1110] [더하기 사이클]
출제 링크 : https://www.acmicpc.net/problem/1110
1110번: 더하기 사이클
0보다 크거나 같고, 99보다 작거나 같은 정수가 주어질 때 다음과 같은 연산을 할 수 있다. 먼저 주어진 수가 10보다 작다면 앞에 0을 붙여 두 자리 수로 만들고, 각 자리의 숫자를 더한다. 그 다음, 주어진 수의 가장 오른쪽 자리 수와 앞에서 구한 합의 가장 오른쪽 자리 수를 이어 붙이면 새로운 수를 만들 수 있다. 다음 예를 보자. 26부터 시작한다. 2+6 = 8이다. 새로운 수는 68이다. 6+8 = 14이다. 새로운 수는 84이다. 8+4 =
www.acmicpc.net
코드
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using static System.Console; | |
using System.Text; | |
using System.IO; | |
namespace baekjoon | |
{ | |
class MainApp | |
{ | |
static void Main() | |
{ | |
string inputNum = Console.ReadLine(); // 처음 입력값 | |
int count = 0; // 반복될 횟수가 저장될 변수 | |
int addNum; // 첫째자리와 둘째자리가 더해진 값이 저장될 변수 | |
if (10 > int.Parse(inputNum)) // 10보다 작을때 0을 붙여 두 자리 수로 만들기 | |
{ | |
inputNum = inputNum + 0; //"string 값" + "0" 은 문자열로 붙게됨 | |
// "9" + 0 = "90" | |
} | |
string originalNum = inputNum; // 저장될 원본 입력값 | |
while (true) | |
{ | |
count++; | |
int a = int.Parse(inputNum) / 10; // 첫째 자리 | |
int b = int.Parse(inputNum) % 10; // 둘째 자리 | |
addNum = a + b; // 첫째 자리 + 둘째 자리 | |
inputNum = b.ToString() + (addNum % 10).ToString(); | |
// b.ToString() => b값을 string값으로 받고 | |
// (addNum % 10).ToString() => 더해진 값의 두번째 자리를 string으로 받고 | |
// 두 값은 string 값이므로 문자열로 붙게됨 | |
if (int.Parse(inputNum) == int.Parse(originalNum)) break; | |
// string 값으로 더해진 inputNum 과 변하지 않은 처음 입력값 originalNum을 비교하여 같으면 | |
// while문 탈출 | |
} | |
WriteLine(count); // 반복된 횟수 | |
} | |
} | |
} |
반응형