Timo66

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Add / Divide / Multiply / Power / Plus / Sqrt

Question 1

Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

Remember to use a carry and check carry in the very last part. And initiate a -1 result listNode is very clear. 

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
11         if (l1 == null)
12             return l2;
13         if (l2 == null)
14             return l1;
15         
16         int carry = 0;
17         ListNode res = new ListNode(-1);
18         ListNode head = res;
19         while (l1!=null || l2 != null){
20             int sum = carry;
21             if (l1 != null){
22                 sum += l1.val;
23                 l1 = l1.next;
24             }
25             if (l2 != null){
26                 sum += l2.val;
27                 l2 = l2.next;
28             }
29             carry = sum/10;
30             res.next = new ListNode(carry==1 ? sum%10 : sum);
31             res = res.next;
32         }
33         if (carry == 1)
34             res.next = new ListNode(carry);
35         return head.next;
36     }
37 }

Question 2

Add Binary

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

We can use stringBuffer here too with append() and reverse(), which can save time as string + is copy first then add. 

 1 public String addBinary(String a, String b) {
 2         if (a==null)
 3             return b;
 4         if (b==null)
 5             return a;
 6         
 7         int carry = 0;
 8         int sum = 0;
 9         String res = "";
10         int i = a.length()-1;
11         int j = b.length()-1;
12         
13         while (i >= 0 || j >=0){
14             sum = carry;
15             if (i >= 0){
16                 sum += a.charAt(i) - '0';
17                 i --;
18             }
19             if (j >= 0){
20                 sum += b.charAt(j) - '0';
21                 j --;
22             }
23             carry = sum/2;
24             sum = sum%2;
25             res = sum + res;
26         }
27         if (carry == 1)
28             res = "1" + res;
29         return res;
30     }

Question 3

Divide Two Integers

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

If we cannot use * / %, we can consider using +. Remember to deal with overflow problem. 

 1 public int divide(int dividend, int divisor) {
 2         if (dividend == 0 || divisor == 0) {  
 3             return 0;  
 4         }  
 5         boolean isNeg = (dividend > 0 && divisor < 0)  
 6                 || (dividend < 0 && divisor > 0);  
 7         long a = Math.abs((long) dividend);  
 8         long b = Math.abs((long) divisor);  
 9         if (b > a) {  
10             return 0;  
11         }  
12   
13         long sum = 0;  
14         long pow = 0;  
15         long result = 0;  
16         while (a >= b) {  
17             pow = 1;  
18             sum = b;  
19             while (sum + sum <= a) {  
20                 sum += sum;  
21                 pow += pow;  
22             }  
23             a -= sum;  
24             result += pow;  
25         }  
26         
27         if (isNeg){
28             if (-result < Integer.MIN_VALUE){
29                 return Integer.MAX_VALUE;
30             }
31         }
32         else {
33             if (result > Integer.MAX_VALUE){
34                 return Integer.MAX_VALUE;
35             }
36         }
37         
38         return isNeg ? -(int)result : (int)result;  
39

Question 4

Multiply Strings

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note: The numbers can be arbitrarily large and are non-negative.

A very important trick here is use another int[] array to record each digit's multiply result. And the int length is the i + j length. Althoughghtit may larger thatn the actual length of the result, the result stringBuilder we use will delete all the zero value at the begining of the string. 

And the stringBuilder has insert() and delete(), and can insert a digit before all result, which is very convenient. 

 1 public String multiply(String num1, String num2) {
 2         if (num1 == null || num2 == null)
 3             return null;
 4         if (num1.equals("0") || num2.equals("0"))
 5             return "0";
 6         
 7         String n1 = new StringBuilder(num1).reverse().toString();
 8         String n2 = new StringBuilder(num2).reverse().toString();
 9         
10         int[] d = new int[n1.length() + n2.length()];
11         
12         for (int i = 0; i < n1.length(); i ++){
13             for (int j = 0; j < n2.length(); j ++){
14                 int a = n1.charAt(i)-'0', b = n2.charAt(j)-'0';
15                 d[i+j] += a*b;
16             }
17         }
18         
19         StringBuilder res = new StringBuilder();
20         int carry = 0;
21         int digit = 0;
22         for (int i : d){
23             digit = (i + carry)%10;
24             carry = (i+carry) / 10;
25             res.insert(0,digit);
26         }
27         if (carry != 0)
28             res.insert(0,carry);
29         
30         while (res.length() > 0 && res.charAt(0) == '0')
31             res.deleteCharAt(0);
32         
33         return res.toString();
34

Question 5

Pow(x, n)

Implement pow(xn).
It is very clear use the binary search to reduce the calculation complex and use half/x*half to deal with the negative power. So if the n < 0, it will let it divide the x instead of mutiply, but it also equals to * 1/x;
 1 public double myPow(double x, int n) {
 2         if (n==0)
 3             return 1;
 4         double half = myPow(x,n/2);
 5         if (n % 2 == 0)
 6             return half * half;
 7         else if (n > 0)
 8             return half * half * x;
 9         else
10             return half/x*half;
11     }

Question 6

Plus One

Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

A trick here is if the carry remains 1 till the end, only the most significant bit is 1, while others are all 0. Because it only adds one not other value.

 1 public int[] plusOne(int[] digits) {
 2         if (digits == null || digits.length == 0)
 3             return digits;
 4         
 5         int carry = 1;
 6         int sum = 0;
 7         for (int i = digits.length-1; i >= 0; i --){
 8             sum = carry + digits[i];
 9             carry = sum/10;
10             digits[i] = sum%10;
11         }
12         if (carry == 0)
13             return digits;
14         
15         int[] res = new int[digits.length+1];
16         res[0] = 1;
17         return res;
18     }

Go to have dinner with xl, so did not finish it at time.

Question 7

Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

Be careful you may met a /zero error here if you start by left = 0; 

while you set left = 1, and right >=left, so right >=1, (left + right)/2 >=1 will not be zero.

 1 public int mySqrt(int x) {
 2         if (x == 0)
 3             return x;
 4         
 5         int left = 1;
 6         int right = x;
 7         int mid;
 8         int res = 0;
 9         while (left <= right){
10             mid = (left + right)/2;
11             if(x/mid>=mid){
12                 left = mid +1 ;
13                 res = mid;
14             }
15             else 
16                 right = mid -1;
17         }
18         return res;
19     }

 

posted on 2015-07-22 09:09  Timo66  阅读(282)  评论(0编辑  收藏  举报