Wednesday, 15 July 2015

Java Programs Made Easy

Q).. A number is given as input. 
Find the odd digits in the number,
 add them and find if the sum is odd or not.
if even return -1, if odd return 1
input:52315
logic:5+3+1+5=14(even)
output:-1
input:1112
logic:1+1+1=3(odd)
output:1

  1. package Set1;
  2. public class ClassSet1 {
  3.  public static int SumOfOddsAndEvens(int n){
  4.   int n1,n2=0,n3;
  5.   while(n!=0)
  6.   {
  7.    n1=n%10;
  8.    if((n1%2)!=0)
  9.     n2+=n1;
  10.    n/=10;
  11.   }
  12.   if(n2%2==0)
  13.    n3=-1;
  14.   else
  15.    n3=1;
  16.   
  17.   return n3; 
  18.  }
  19.  public static void main(String[] args) {
  20.   int n=12346;
  21.   System.out.println(SumOfOddsAndEvens(n));
  22.  }
  23. }