Common Pitfalls

Tedious

One sample tedious programming question:

  • product / divide / sum/ subtract might lead to intermediate result greater than int. prevent overflow
  • ask about boundaries, null, length==0
  • Append / initialization help simplify coding
  • read-in a num of unknown #digits from string
  • End Of String handling or last operation.... (i==s.length()-1)

227. Basic Calculator II

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.

You may assume that the given expression is always valid.

Some examples:
"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5
class Solution {
    public int calculate(String s) {
        if(s==null || s.length()==0) return 0;

        long sum = 0, val = 0, prevNum = 0;
        char prevSign = '+';

        for(int i=0; i<s.length(); i++) {
            if(Character.isDigit(s.charAt(i))) {
                val = val*10 + (s.charAt(i) - '0');
            }
            if(!Character.isDigit(s.charAt(i)) && s.charAt(i)!=' ' || i==s.length()-1) {
                switch(prevSign) {
                    case '+': sum += prevNum; prevNum = val; break;
                    case '-': sum += prevNum; prevNum = -1*val; break;
                    case '*': prevNum *= val; break;
                    case '/': prevNum /= val; break;
                }

                prevSign = s.charAt(i);
                num = 0;
            }
        }

        return (int)(sum+prevNum);
    }
}

Pay attention to seem minor description

565. Array Nesting

A zero-indexed array A of length N contains all integers from 0 to N-1. Find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], ... } subjected to the rule below.

Suppose the first element in S starts with the selection of element A[i] of index = i, the next element in S should be A[A[i]], and then A[A[A[i]]]… By that analogy, we stop adding right before a duplicate element occurs in S.

Example 1:

Input:
 A = [5,4,0,3,1,6,2]

Output:
 4

Explanation:

A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2.

One of the longest S[K]:
S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0}

Note:

  1. N is an integer within the range [1, 20,000].
  2. The elements of A are all distinct.
  3. Each element of A is an integer within the range [0, N-1].

results matching ""

    No results matching ""