Smallest Greatest number- Solution for level2 coding challenge of June 2013 by Techgig

Niladri.Biswas
Posted by in C# category on for Beginner level | Points: 250 | Views : 2643 red flag

In this article we will look into the solution of Smallest Greatest number- a Level 2 coding challenge by Techgig

Introduction

Techgig is a global programming community and every month they conduct coding contest.This month they propose a challenge by the name Smallest Greatest number.It is a Level-2 challenge. In this article we will see the my solution for the same.

The Problem Statement

Solution

class Program
{
	static void Main(string[] args)
	{
		int result = smallest_number(2345);
	}

	public static int smallest_number(int input1)
	{		
		int n1, n2;
		int d1 = MultiplyToOneDigit(input1, out n1),
			d2 = SumToOneDigit(input1, out n2);		

		for (int i = input1 + 1; i < 1000000000; i++)
		{
			int value, steps;
			
			value = MultiplyToOneDigit(i, out steps);
			if (value != d1 || steps > n1) continue; // no good
			
			value = SumToOneDigit(i, out steps);
			if (value != d2 || steps > n2) continue; // no good

			return i;
		}
		return -1; // no answer
	}

	static int MultiplyToOneDigit(int value, out int steps)
	{
		steps = 0;
		while (value > 10)
		{
			value = MultiplyDigits(value);
			steps++;
		}
		return value;
	}
	static int SumToOneDigit(int value, out int steps)
	{
		steps = 0;
		while (value > 10)
		{
			value = SumDigits(value);
			steps++;
		}
		return value;
	}
	static int MultiplyDigits(int value)
	{
		int acc = 1;
		while (value > 0)
		{
			acc *= value % 10;
			value /= 10;
		}
		return acc;
	}
	static int SumDigits(int value)
	{
		int total = 0;
		while (value > 0)
		{
			total += value % 10;
			value /= 10;
		}
		return total;
	}        
}

First we are finding the Single digit after Multilication of the supplied number.Next we are finding the Single digit after Summation of the supplied number.

Then we are comparing that with other numbers and if there is a positive result, we are displaying that.

Conclusion

I hope that this will be a good learning exercise for those whose are beginners in C#.Also participating in challenges helps us to hone our skills.Thanks for reading.

Disclaimer: This solution has been personally prepared by me and submitted for the knowledge sharing purpose.

Page copy protected against web site content infringement by Copyscape

About the Author

Niladri.Biswas
Full Name: Niladri Biswas
Member Level: Platinum
Member Status: Member
Member Since: 10/25/2010 11:04:24 AM
Country: India
Best Regards, Niladri Biswas
http://www.dotnetfunda.com
Technical Lead at HCL Technologies

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)