Design and implement an algorithm that takes two nonnegative
Design and implement an algorithm that takes two non-negative integers x and y (in base 2, represented as lists of their binary digits), returns true when x y and false, otherwise. Test your program on these pairs of numbers (given already as lists):
(a) x=[]andy=[]
(b) x=[]andy=[1,1,0]
(c) x=[1,1]andy=[]
(d) x = [1,1,0,1,0,1,1,0,1,1] and y = [1,1,0,1,1,1,1,0,1,1] (
e) x = [1,0,0,1,1,1,0,1,1] and y = [1,0,0,1,1,1,0,1,1]
(f) x = [0,0,0,1,1,1,1,0,1,1,1] and y = [1,1,0,0,1,1,1,1,0,1]
(g) x = [1,1,0,1] and y = [1,1,1,1,0,1]
Solution
I\'ve implemented the alrogithm in java. Here is the class with a main function and the algorithm.
Algorithm:
Step1: START
Step2: Get the inputs x[] and y[]
Step3: INIT lengthofX, lengthofY, NumberX, NumberY
Step4: IF x == null, lengthofX = 0 ELSE lengthofX = len(x). Do the same for Y.
Step5: FOR every number in X[] move it to NumberX. Do the same for Y.
Step6: IF NumberX >=NumberY print true ELSE print false
Step7: STOP
Implementation:
package Sample;
public class BinaryCheckAlgorithm {
public static boolean isGreater(int x[], int y[])
{
boolean isGreater = false;
int lengthOfX = x==null? 0: x.length;
int lengthOfY = y==null? 0: y.length;
if(lengthOfX == 0 && lengthOfY == 0)
{
isGreater = true;
}
else if(lengthOfX == 0 && lengthOfY > 0)
{
isGreater = false;
}
else if(lengthOfX > 0 && lengthOfY == 0)
{
isGreater = true;
}
else
{
int numberOfBits = (lengthOfX>lengthOfY)? lengthOfX : lengthOfY;
String stringX = \"\", stringY = \"\";
int numberX = 0, numberY = 0;
int missingBitsForX = numberOfBits - lengthOfX;
int missingBitsForY = numberOfBits - lengthOfY;
for(int i=0; i<missingBitsForX; i++)
{
stringX = stringX + \"0\";
}
for(int i=0; i<missingBitsForY; i++)
{
stringY = stringY + \"0\";
}
for(int i=0; i<lengthOfX; i++)
{
stringX = stringX + x[i];
}
for(int i=0; i<lengthOfY; i++)
{
stringY = stringY + y[i];
}
numberX = Integer.valueOf(stringX);
numberY = Integer.valueOf(stringY);
if(numberX>=numberY)
{
isGreater = true;
}
}
return isGreater;
}
public static void main(String args[])
{
int ax[] = null, ay[] = null;
System.out.println(isGreater(ax,ay));
int bx[] = null, by[] = {1,10};
System.out.println(isGreater(bx, by));
int cx[] = {1,1}, cy[] = null;
System.out.println(isGreater(cx, cy));
int dx[] = {1,1,0,1,0,1,1,0,1,1}, dy[] = {1,1,0,1,1,1,1,0,1,1};
System.out.println(isGreater(dx, dy));
int ex[] = {1,0,0,1,1,1,0,1,1}, ey[]={1,0,0,1,1,1,0,1,1};
System.out.println(isGreater(ex, ey));
int fx[] = {0,0,0,1,1,1,1,0,1,1,1}, fy[] = {1,1,0,0,1,1,1,1,0,1};
System.out.println(isGreater(fx, fy));
int gx[]={1,1,0,1}, gy[] = {1,1,1,1,0,1};
System.out.println(isGreater(gx, gy));
}
}
OUTPUT:
true
false
true
false
true
false
false



