Given the number of digits in a number is even.Write a program to compare the first half with the second half.
e.g. given345678 , compare 345 and 678.
There can be two approaches to solve the above problem:
Method1:
public int splitAndCompare(int n)
{
Integer i=n;
int len= i.toString().length();
int powerTen=this.getPowerten(10, len/2);
int fhalf=n/powerTen;
int shalf=n-fhalf*powerTen;
System.out.println(fhalf);
System.out.println(shalf);
if(fhalf<shalf)
{
return -1;
}
else if(fhalf>shalf)
{
return 1;
}
else
return 0;
}
public int getPowerten(int num,int len)
{int x=1;
while(x<len)
{
num=num*10;
x++;
}
return num;
}
}
Method2:
public int numHalfCom(int n)
{
Integer i=n;
int len=i.toString().length();
String str=i.toString();
String str1=str.substring(0, len/2);
String str2=str.substring(len/2,len);
int fhalf=Integer.parseInt(str1);
int shalf=Integer.parseInt(str2);
System.out.println(fhalf);
System.out.println(shalf);
if(fhalf<shalf)
{
return -1;
}
else if(fhalf>shalf)
{
return 1;
}
else
return 0;
//Integer fnum=str1;
}
Happy Coding :)
e.g. given345678 , compare 345 and 678.
There can be two approaches to solve the above problem:
Method1:
public int splitAndCompare(int n)
{
Integer i=n;
int len= i.toString().length();
int powerTen=this.getPowerten(10, len/2);
int fhalf=n/powerTen;
int shalf=n-fhalf*powerTen;
System.out.println(fhalf);
System.out.println(shalf);
if(fhalf<shalf)
{
return -1;
}
else if(fhalf>shalf)
{
return 1;
}
else
return 0;
}
public int getPowerten(int num,int len)
{int x=1;
while(x<len)
{
num=num*10;
x++;
}
return num;
}
}
Method2:
public int numHalfCom(int n)
{
Integer i=n;
int len=i.toString().length();
String str=i.toString();
String str1=str.substring(0, len/2);
String str2=str.substring(len/2,len);
int fhalf=Integer.parseInt(str1);
int shalf=Integer.parseInt(str2);
System.out.println(fhalf);
System.out.println(shalf);
if(fhalf<shalf)
{
return -1;
}
else if(fhalf>shalf)
{
return 1;
}
else
return 0;
//Integer fnum=str1;
}
Happy Coding :)