Make larger number from a given number inC#

Given a number whose digits are unique, find the next larger number that can be formed with those digits. For example input is 687 then output will be 876. Our logic is first find out individual digits then sort them and you’ll get largest number that can be generated from given number.

class Make_Larger_Number_From_Given_Number
{
static void Main(string[] args)
{
int num = 7528;
int largeNum = FindMaxNumber(num);
Console.WriteLine(string.Format(“Larger number generated from given number {0} is: {1}”, num, largeNum));
Console.ReadKey();
}

// Our Logic is to first findout all the digits then sort them
private static int FindMaxNumber(int num)
{
List<int> arr = new List<int>();

// Getting individual digits
while (num > 0)
{
arr.Add(num % 10);
num = num / 10;
}

// Sort these individual digits
int temp = 0;
for (int i = 0; i < arr.Count(); ++i)
{
for (int j = 0; j < arr.Count(); ++j)
{
temp = 0;
if (arr[i] > arr[j])
{
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}

// Reverse arr Array and we’ll have our large number
string largeNumber = string.Empty;
for (int i = 0; i < arr.Count(); ++i)
{
largeNumber += arr[i].ToString();
}

return Convert.ToInt32(largeNumber);
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s