Advertisement
Guest User

Last non zero of factorial.

a guest
Apr 9th, 2013
419
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.45 KB | None | 0 0
  1. import java.io.*;
  2.  
  3. public class Challenge1 {
  4.    
  5.    
  6.     public static int Factorial(int number)
  7.     {
  8.         int temp;
  9.         if(number <= 1)
  10.         {
  11.             return 1;
  12.         }
  13.         temp = number* Factorial(number -1);
  14.         return temp;
  15.     }
  16.    
  17.     public static int FindLastNonZero(int number)
  18.     {
  19.         int foundNumber = number;
  20.         int count = 0;
  21.        
  22.         //Convert number to an array of integers
  23.        
  24.         //First: find how long the array will be
  25.         while(foundNumber != 0)
  26.         {
  27.             foundNumber /= 10;
  28.             count++;
  29.         }
  30.         // create the new array based off of the found length
  31.         int numberArray[] = new int[count];
  32.        
  33.         count = 0;
  34.         foundNumber = number;
  35.        
  36.         //Create the array and put the last digit into the first position.
  37.         // i.e.  1024   array[0] = 4, array[1] = 2, array[2] =0, etc...
  38.         while (foundNumber != 0)
  39.         {
  40.             numberArray[count] = foundNumber % 10;
  41.             foundNumber /= 10;
  42.             count++;
  43.         }
  44.        
  45.         int position=0;
  46.        
  47.         // iterate through the array to find the last non-zero integer
  48.         while (numberArray[position] == 0)
  49.         {
  50.              position++;
  51.         }
  52.        
  53.         return numberArray[position];
  54.     }
  55.  
  56.     public static void main(String [] args) throws NumberFormatException, IOException
  57.     {
  58.         int inputNum;
  59.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  60.         inputNum = Integer.parseInt(br.readLine());
  61.        
  62.         System.out.println("Factorial Result= " + Factorial(inputNum));
  63.        
  64.         System.out.println("Last non-zero integer= " + FindLastNonZero(Factorial(inputNum)));
  65.        
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement