Rakesh Kumar
BAN USERSimple Algorithm:
Assuming L1 and L2 are given and sum is stored in L3
1. Reverse L1;
2. Reverse L2;
3. put=0;keep=0;
4. While (L1 or L2)
sum=L1.data + L2.data + keep;
if(sum >10) then put=sum-10; keep=1
else put=sum; keep=0
L3.insert(put)
L1.moveForward
L2.moveForward
End While;
if(keep!=0) then L3.insert(keep)
//take care of condition when either L1 or L2 becomes empty
5. L3.reverse
6. return L3
I guess this solution will work
public static int findMedian(int arr1[], int arr2[])
{
int length=arr1.length;
int result=length/2;
int n1,n2;
n1=n2=length/2;
while(result<length)
{
if(arr1[n1]==arr2[n2])
{
System.out.printf("came here 1:%d and %d \n", n1,n2);
result=n1+n2;
}
else if(arr1[n1] > arr2[n2])
{
System.out.printf("came here 2:%d and %d \n", n1,n2);
n1=n1- n1/2;
result=result+ n2/2;
n2=n2+n1/2;
}
else if(arr1[n1]<arr2[n2])
{
System.out.printf("came here 3:%d and %d \n", n1,n2);
result=result+n1/2;
n1=n1+n2/2;
n2=n2-n2/2;
}
}
return max(arr1[n1],arr2[n2]);
}
I guess this solution will work
- Rakesh Kumar November 30, 2009public static String trimSpaces(String str)
{
StringBuilder sb=new StringBuilder();
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)==' ')
sb.append(str.charAt(i));
while(str.charAt(i)==' ')
i++;
sb.append(str.charAt(i));
}
return sb.toString();
}
Here is my code with explanation
public static String toRoman(int num)
{
String result="";
String symbols[]={"M","D","C","L","X","V","I"};
int values[]={1000,500,100,50,10,5,1};
while(num > 0)
{
for (int i=0;i<values.length;i++)
{
if(values[i] <=num)
{
//Next gets the next symbol candidate, which can precede the current symbol
//to skip symbols like L and V I am incrementing it by i%2
int next=i+ i%2;
//if values[i] < current number, we see if it can be represented
//in the form where a smaller symbol precedes it
//for that, if we are at i, we subtract the value of next symbol candidate a[next]
//from a[i-1]
//if its less than equal to the number than we use the combination of
//a[next] and a[i-1] to represent the roman no otherwise not
//example:num=40 i=2, a[i-1]=50, a[next]=10 so a[i-1]-a[next]=40, we can use the
//above convention here
//but for number 30, a[i-1]-a[next] gives 40 (same as above) which is greater than 30
//hence we follow the normal convetion here (the else block in the below code)
if ( (i>0) && (next<values.length) &&
(values[i-1]-values[next] <=num))
{
result=result+ symbols[next]+symbols[i-1];
num = num + values[next] - values[i-1] ;
i=-1; //setting the i to -1 helps in further checking of the if conditions
}
else
{
result+=symbols[i];
num-=values[i];
i=-1;
}
}
}
}
return result;
}
he just needs to check at the end whether stack is empty or not and not before every push
- Rakesh Kumar June 13, 2011