google code prettify

顯示具有 LeetCode 標籤的文章。 顯示所有文章
顯示具有 LeetCode 標籤的文章。 顯示所有文章

2016年7月16日 星期六

LeetCode - 371. Sum of Two Integers

Question:

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example:
Given a = 1 and b = 2, return 3.

Solution:


public class Solution {
    public int getSum(int a, int b) {
        return a+b;
    }
}

LeetCode - 374. Guess Number Higher or Lower

Question:

We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You have to guess which number I picked.
Every time you guess wrong, I'll tell you whether the number is higher or lower.
You call a pre-defined API guess(int num) which returns 3 possible results (-11, or 0):

Solution:


public class Solution extends GuessGame {
    
    public int guessNumber(int n) {
        Long R = new Long(n);
  Long L = 1L;
   
  if(R!=L){
   while(R>=L){
    Long mid = ((L+R)>>1);

    int result = guess(mid.intValue());
    //System.out.println("mid:" + mid + " ,result:" + result);
    if(result ==1){
     L = mid+1;
     
    }else if(result ==-1){
     R = mid-1;
    }else{
        return mid.intValue();
    }
   }
  }else{
      return R.intValue();
  }
  
  
  return L.intValue();
  
 }
}

LeetCode - 20. Valid Parentheses

Question:

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

Solution:


public class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
  
  char[] array = s.toCharArray();
  if (array.length % 2 != 0) {
   return false;
  }
  
  for(int i =0;i<array.length;i++){
   char c = array[i];
   if(c=='(' || c=='[' || c=='{'){
    stack.push(c);
    continue;
   }
   
   if(stack.isEmpty()==true){
    return false;
   }
   
   if(c==')'){
    if (stack.pop()!='(')
     return false;
   }else if(c==']'){
    if(stack.pop()!='[')
     return false;
   }else if(c=='}'){
    if(stack.pop()!='{')
     return false;
   }else{
    return false;
   }
  }
  
  if(stack.isEmpty()==false){
   return false;
  }else{
   return true;
  }
    }
}