vendredi 20 octobre 2023

The Next methode should return the smallest integer which is > n

 The Next methode should return the smallest integer which is > n , and whose digits are different from all n's digits


Ex:

Console.WriteLine(Solution.Next(2)); // 3
Console.WriteLine(Solution.Next(901));// 2222
Console.WriteLine(Solution.Next(958));// 1000
Console.WriteLine(Solution.Next(3025));// 4111
Console.WriteLine(Solution.Next(654321));// 700000



// C# code​​​​​​‌​‌​​‌‌​‌‌‌​​​‌​‌​‌​‌​​​‌ below

using System;

using System.IO;

using System.Collections.Generic;

using System.Collections;

using System.Linq;

using System.Text;

using System.Threading;


class Solution

{

    public static int Next(int n)

    {

        if(n <= 0){

            throw new ArgumentException("n must be integer possitive");

        }

        int m = n + 1;

        while (!CompareDigits2number(n,m)){

            m = m +1;

        }        

        if(m >= Math.Pow(2,31)){

            return -1;

        }

        return m;

    }


    public static char[] numberToArray(int n){

        var nStr = n.ToString();

        var nArray = new char[nStr.Length];

        for(int i = 0; i < nStr.Length; i++){

            nArray[i] = nStr[i];

        }

        return nArray;

    }


    public static bool CompareDigits2number(int n, int m){

        var arrayN = numberToArray(n);

        var arrayM = numberToArray(m);


        foreach(var item in arrayN){

            if(arrayM.Contains(item)){

                return false;

            }

        }

        return true;

    }

}

Aucun commentaire:

Enregistrer un commentaire