Wednesday, 15 June 2016

Program to find the least among 4 numbers.

If 20,33,5,77 are the given numbers then 5 must be returned.

Code:

public class LeastNumberFrom4
{
    public static void main(String[] args)
   {
        int n1 = 20;
        int n2 = 33;
        int n3 = 5;
        int n4 = 77;
        System.out.println(getLeastNumber(n1, n2, n3, n4));
    }

    public static int getLeastNumber(int num1 , int num2, int num3, int num4)
   {
         int least;
         int[] n = {num1,num2,num3,num4};
         least = Integer.MAX_VALUE;
         for(int i =0;i<n.length;i++)
         {
            if(least > n[i])
             {
                        least = n[i];
              }
          }
             return least;
     }
 }

Program to reverse an Integer using StringBuffer class.

If n1=16, n2=26 then output must be 321.
Explanation: 16,26 should be reversed as 61,62 and added.
Then addition result should be reversed and printed.    

Code:

public class Stringbuffer
{
   public static void main(String[] args)
  {
        StringBuffer sb=new StringBuffer("16");
        StringBuffer sb1=new StringBuffer("26");
        StringBuffer sb2;
       
        sb.reverse();
        sb1.reverse();
       
        String s=sb.toString();
        int n1=Integer.parseInt(s);
       
        String s1=sb1.toString();
        int n2=Integer.parseInt(s1);
       
        int n3=n1+n2;
               
        sb2=new StringBuffer();
        sb2.append(n3);
        sb2.reverse();
        String s3=sb2.toString();
        int n4=Integer.parseInt(s3);
        System.out.println(n4);
    }
}