典型90問    次の典型90問へ    前の典型90問へ

典型90問 067 Base 8 to 9(★2)


問題へのリンク


C#のソース

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static string InputPattern = "InputX";

    static List<string> GetInputList()
    {
        var WillReturn = new List<string>();

        if (InputPattern == "Input1") {
            WillReturn.Add("21 1");
            //15
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("1330 1");
            //555
        }
        else if (InputPattern == "Input3") {
            WillReturn.Add("2311640221315 15");
            //474547
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    static void Main()
    {
        List<string> InputList = GetInputList();
        string[] SplitArr = InputList[0].Split(' ');

        string N = SplitArr[0];
        int K = int.Parse(SplitArr[1]);

        long DecVal = Change8To10(N);
        for (int I = 1; I <= K; I++) {
            string Str9 = Change10To9(DecVal);
            Str9 = Str9.Replace('8', '5');
            DecVal = Change8To10(Str9);

            if (I == K) {
                Console.WriteLine(Str9);
            }
        }
    }

    // 10進数を9進数に変換して返す
    static string Change10To9(long pDecVal)
    {
        if (pDecVal == 0) return "0";

        var ModList = new List<long>();
        while (pDecVal > 0) {
            long Mod = pDecVal % 9;
            ModList.Add(Mod);
            pDecVal /= 9;
        }
        ModList.Reverse();

        var sb = new System.Text.StringBuilder();
        ModList.ForEach(pX => sb.Append(pX));
        return sb.ToString();
    }

    // 8進数を10進数に変換して返す
    static long Change8To10(string pStr)
    {
        long WillReturn = 0;
        long Omomi = 1;
        for (int I = pStr.Length - 1; 0 <= I; I--) {
            WillReturn += (pStr[I] - '0') * Omomi;
            Omomi *= 8;
        }
        return WillReturn;
    }
}


解説

ナイーブに進数変換してます。