ConvertToBase7.cs

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
					
public class Program
{
    /* 
     * Example: 100; Base = 7
     * 100 / 7 = 14; 100 % 7 = 2
     * 14 / 7 = 2; 14 % 7 = 0
     * 2 / 7 = 0; 2 % 7 = 2
     * Output: 202
    */	
	public static string ConvertToBase7(int num) 
	{
        if (num == 0)
            return "0";
        
        int sign = num >= 0 ? 1 : -1;
        num *= sign;
        
        var res = new List<int>();
        while (num > 0)
        {
            res.Add(num % 7);
            num /= 7;
        }
        
        res.Reverse();
        string str = string.Join("", res);
        return sign == -1 ? "-" + str : str;
    }
	
	public static void Main()
	{
		Console.WriteLine("UniLecs");
		
		// tests
		Console.WriteLine(ConvertToBase7(6).ToString()); // 6
		Console.WriteLine(ConvertToBase7(7).ToString()); // 10
		Console.WriteLine(ConvertToBase7(8).ToString()); // 11
		
		Console.WriteLine(ConvertToBase7(100).ToString()); // 202
	}
}
;