Amazon interview question

1 ) Algorithm to compute square root that handles perfect and non-perfect squares. 2) Reverse a LinkedList

Interview Answers

Anonymous

24 Dec 2014

package com.coding.tests; public class SquareRoot { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int X = 625; int Y = 771; System.out.println(sqrt(X)); System.out.println(sqrt(Y)); } //sqrt(S): Xn+1=(Xn+S/Xn)/2; public static int sqrt(int X){ if(X==0) return 0; boolean isNegtive=X<0?true:false; int S = Math.abs(X); int Xn = X/2; int preXn=Xn; do{ preXn=Xn; Xn=(Xn+S/Xn)/2; }while((Xn-preXn)!=0); return isNegtive?0-Xn:Xn; } }

Anonymous

24 Dec 2014

package com.coding.tests; public class ReverseLinkedList { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Node n1= new Node(1); n1.next=new Node(2); n1.next.next=new Node(3); n1.next.next.next=new Node(4); Node res = reverseLinkedList(n1); while(res!=null){ System.out.print(res.val+" "); res=res.next; } } public static Node reverseLinkedList(Node head){ if(head==null) return null; if(head.next==null) return head; Node pre=head, current=head.next; pre.next=null; while(current!=null){ Node p = current; current=current.next; p.next=pre; pre=p; } return pre; } private static class Node{ int val; Node next; public Node(int value){ val=value; } } }