tmsagila
BAN USERTo find out if 25 is a perfect square, i have to find a number which is greater than 1 but less than n=25 which n= 25
will be divisible by and when that number is multiplied by itself then it should be equal to n=25;
in my method;
n = value
the number that n should be divisible by = div;
so div * div == value and value%div == 0;
the for loop accomplishes div*div using addition instead;
complexity root n * root n = n (not sure on this one, help is appreciated);
public boolean isperfectSquare(int value,int div){
int temp = 0;
if(div >= value){
return false;
}
for(int i=div; i>0 ; i--){
temp = temp+div;
}
if(temp == value){
return true;
}else{
return isperfectSquare(value,div+1);
}
}
oh and the editor changes the code for this line for(int i=div; i>;0 ; i--) resulting in wrong java syntax when i post it right, not sure why.
i have improved my solution to be root n complexity; the solution is based on that 4+5 = 9 , 9+7 = 16,16+9 = 25,25+11 = 36 and so on..
public boolean isperfectS(int value){
int nextsquare = 4;
int diff = 3;
while( nextsquare <= value){
if (nextsquare == value){
return true;
}
diff = diff + 2;
nextsquare = nextsquare + diff;
}
return false;
}
public static Integer addList(LinkedList listone, LinkedList listtwo){
int carryover = 0;
int tempsum = 0;
int carryoverindex = 0;
StringBuilder sumbuild = new StringBuilder();
for(int i=listone.size()-1;i>=0;i--){
if((carryoverindex - 1) != i){
carryover = 0;
}
tempsum = (int)listone.get(i) + (int)listtwo.get(i) + carryover;
if(tempsum > 9 && (i != 0)){
carryoverindex = i;
carryover = (tempsum-(tempsum - 10))/10;
tempsum = tempsum - 10;
if (carryover == 0){
carryover = 1;
tempsum = 0;
}
}
//System.out.println(sumbuild+" "+i+" "+"before "+tempsum);
sumbuild.append(tempsum);
}
return Integer.parseInt((sumbuild.reverse()).toString());
}
if there is a limitation on extra memory then Node temp, and data compare would need to be passed to the isPalindrome class. (i didnt realize that i had not logged in when i posted the solution before)
public boolean isPalindrome(Node head, Node temp, char compare){
while(head != null){
compare = head.data;
temp = head;
while(temp.next != null){
temp = temp.next;
compare = temp.data;
}
temp = null;
if(!((head.data).equals(compare)){
return false;
}
head = head.next;
}
return true;
}
the way i understand the question is that you need to only compare the neighboring strings. so i will compare the last character in first string and first character in next string and so on will moving along the list and that will be O(n). if we are only interested in the answer to the question can a chain be formed then returning a boolean seems sufficient.
- tmsagila October 03, 2013