Advertisement
Guest User

ThirdDigit

a guest
Mar 11th, 2015
356
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.88 KB | None | 0 0
  1. // Problem 5. Third Digit is 7?
  2.  
  3. /* Write an expression that checks for given integer if its third digit from right-to-left is 7.
  4.  *
  5.  * Examples:
  6.  *       n  Third digit 7?
  7.  *       5  false
  8.  *     701  true
  9.  *    9703  true
  10.  *     877  false
  11.  *  777877  false
  12.  * 9999799  true  
  13.  */
  14.  
  15. using System;
  16. using System.Collections.Generic;
  17.  
  18. class ThirdDigitSeven
  19. {
  20. /* To extract the value of a digit, GetDigt method does the following:
  21.  * 1. divides the number by Nth power of 10, where N = (position of digit - 1)
  22.  * (please note that ( not only as per this homework instruction), the digit positions increase from left to right
  23.  * so the last digit is at position 1....... (I hate termonology mess... ) )
  24.  * 2. applies the modulus operator %:     (number / (int)Math.Pow(10, digit - 1)) % 10
  25.  * and the remainder of this divition is the digit value
  26.  * for the last (at position 1) digit of 701, for instance, this calculation will be
  27.  * 701 / (int)Math.Pow(10, 1 - 1)) % 10, or (701/1) (zeroth power of 10 = 1) --> 701%10 = 1,
  28.  * and 1 is indeed the value of the digit at position 1
  29.  */
  30.     static int GetDigit(int number, int digit)
  31.     {
  32.         return (number / (int)Math.Pow(10, digit - 1)) % 10;
  33.     }
  34.  
  35.     static void Main()
  36.  
  37.     {
  38.         string intro = @"This program checks
  39. for given integer if its third digit
  40. from right-to-left is 7.";
  41.         Console.WriteLine(intro);
  42.  
  43.         string input;
  44.         int num;
  45.  
  46.         do  // validates number input
  47.         {
  48.             Console.Write("\nPlease enter a type int number: ");
  49.             input = Console.ReadLine();
  50.  
  51.         } while (!int.TryParse(input, out num));
  52.  
  53.         // applies the GetDigit method on digit at position 3 of number num, prints the result
  54.         Console.WriteLine("\nNumber {0}:  Third digit is 7?     {1}\n", num.ToString().PadLeft(12), GetDigit(num, 3) == 7 ? true : false);
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement