How to convert an array of digits to a number in C#

2 Answers

0 votes
using System;

class Program
{
    static int ArrayToNumber(int[] arr) {
        int n = 0;
        
        foreach (int num in arr) {
            n = n * 10 + num;
        }
        
        return n;
    }

    static void Main() {
        int[] arr = { 4, 6, 3, 9, 1, 2 };

        int n = ArrayToNumber(arr);

        Console.WriteLine("n = " + n);
    }
}


/*
run:

n = 463912

*/


answered Apr 7, 2014 by avibootz
edited Jan 10 by avibootz
0 votes
using System;
using System.Linq;

class Program
{
    static int ArrayToNumber(int[] arr) {
        return arr.Aggregate((result, x) => result * 10 + x);
    }

    static void Main() {
        int[] arr = { 4, 6, 3, 9, 1, 2 };

        int n = ArrayToNumber(arr);

        Console.WriteLine("n = " + n);
    }
}


/*
run:

n = 463912

*/

 



answered May 13, 2024 by avibootz
edited Jan 10 by avibootz
...