본문 바로가기
CS/알고리즘

정수의 각 자릿수를 다루는 방법 (C#)

by alpacadabra 2022. 8. 28.

정수 x의 각 자릿수를 순서대로 출력하는 코드는 아래와 같다.

 

public static void Print(int x)
{
    if (x / 10 > 0)
        Print(x / 10);

    Console.Write(x % 10);
}

 


만약 거꾸로 1의 자리부터 출력하고 싶다면 재귀가 아닌 반복문으로도 충분하다.

 

public static void PrintReverse(int x)
{
    while (x > 0)
    {
        Console.Write(x % 10);
        x /= 10;
    }
}

 


거꾸로 된 출력이 아니라 값을 원한다면 아래의 방법을 사용하면 된다.

 

public static int Reverse(int x)
{
    int result = 0;

    while (x > 0)
    {
        result = result * 10 + x % 10;
        x /= 10;
    }

    return result;
}

 


위와 비슷하게 각 자릿수의 합을 구할 수도 있다.

 

public static int Sum(int x)
{
    int result = 0;

    while (x > 0)
    {
        result += x % 10;
        x /= 10;
    }

    return result;
}

 


실행 결과

 

 

(Print에 공백을 추가해 알아보기 쉽게 하였음)

'CS > 알고리즘' 카테고리의 다른 글

정렬 #3) 삽입 정렬  (1) 2022.10.04
정렬 #2) 선택 정렬  (1) 2022.10.04
정렬 #1) 버블 정렬  (1) 2022.10.04
빠른 거듭제곱 알고리즘 (C#)  (0) 2022.08.29
매개 변수 탐색(parametric search, 파라메트릭 서치)  (3) 2022.08.09

댓글