Variable & Control flow

1.[Second Max of Array]http://www.lintcode.com/en/problem/second-max-of-array/
solution:暴力解

class Solution:
    """
    @param: : An integer array
    @return: The second max number in the array.
    """

    def secondMax(self, nums):
        # write your code here
        maxValue = max(nums[0],nums[1])
        secondValue = min(nums[0],nums[1])
        
        for i in xrange(2, len(nums)):
            if nums[i] > maxValue:
                secondValue = maxValue
                maxValue = nums[i]
            elif nums[i] > secondValue:
                secondValue = nums[i]
            else:
                return secondValue
            
        return secondValue
        

2.[Reverse 3-digit Integer]http://www.lintcode.com/en/problem/reverse-3-digit-integer/
solution:利用切片

class Solution:
    """
    @param number: A 3-digit integer 
    @return: Reversed integer 
    """
    def reverseInteger(self, number):
        # write your code here
        # return number % 10 * 100 + number / 10 % 10 * 10 + number / 100
        # return (number - 100) % 10 * 100 + (number - 100) / 10 % 10 * 10 + number / 100
        return int(str(number)[: : -1])

3.[Lowercase to uppercase]http://www.lintcode.com/en/problem/lowercase-to-uppercase/
solution: ascii码, A->65,a->97,0->48

class Solution:
    """
    @param: character: a character
    @return: a character
    """
    def lowercaseToUppercase(self, character):
        # write your code here
        return chr(ord('A') + ord(character) - ord('a'))

4.[Simple Calculator]http://www.lintcode.com/en/problem/simple-calculator/
solution:暴力,和java解法一起

class Calculator:
    """
    @param a, b: Two integers.
    @param operator: A character, +, -, *, /.
    """
    def calculate(self, a, operator, b):
        # Write your code here
        if operator == '+':
            return a + b
        elif operator == '*':
            return a * b
        elif operator == '-':
            return a - b
        elif operator == '/':
            return a / b
@Java
public class Calculator {
    /**
      * @param a, b: Two integers.
      * @param operator: A character, +, -, *, /.
      */
    public int calculate(int a, char operator, int b) {
        switch (operator) {
            case '+': return a + b;
            case '-': return a - b;
            case '*': return a * b;
            case '/': return a / b;
        }
        return 0;
    }
}

你可能感兴趣的:(Variable & Control flow)