palermo4 posted on July 8, 2010 12:24

When I teach my introduction to C# course, I typically provide a tough numeric challenge to stimulate thinking and use all the features of the language learned up to that point.  In a recent class, I was presented the challenge of determining the last number of any integer.  For example:

  • 12 == 2
  • 337 == 7
  • 1000 == 0
  • 987654 == 4

In each example above, I needed to simply return whatever was in the “singles” place – the last number of the number.

My first approach felt like I was cheating, but it worked:

public static int GetLastNumber(string stringifiedNumber)
{
    return Convert.ToInt32(stringifiedNumber[stringifiedNumber.Length -1].ToString());
}// method

After brooding over it, I decided to challenge myself to do this mathematically instead.  Here is the final code:

public static int GetLastNumber(dynamic anyNumber)
{
    double fractional = anyNumber * .1;
    double truncated = Math.Truncate(fractional);
    return (int)(Math.Round((fractional - truncated),1) * 10);
}// method

The use of the dynamic keyword above allows me to pass in any numeric data type.

Updated: Thanks to Nicki for identifying how I over-engineered this problem.  I simply needed to get the modulus of 10 to get what I wanted.  So in one simple statement I could write:

 anyNumber % 10;

Posted in: code  Tags:

Comments


July 8. 2010 20:34
What about just using MOD 10, is that not way less code?

as in
            int x = 1293871238;
            Console.WriteLine(x % 10);

http://jasmanseblog.blogspot.com/http://jasmanseblog.blogspot.com/


July 26. 2010 22:15
Nicki,

Bravo!  Thanks for the much simpler solution!  It never fails that I over-engineer everything Smile

Cheers,

Michael

http://palermo4.com/http://palermo4.com/

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading



Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010 J. Michael Palermo IV