LeetCode question 338 bit counting, 20 valid parentheses, 415 string addition

Table of contents

338-bit bit count

Topic requirements:

Problem-solving ideas:

1. Violence and exhaustion

Code:

2. Solve the N&(N - 1) formula

Code:

3. Solution to the properties of odd and even numbers:

Code:

20 valid brackets

Topic requirements:

Problem-solving ideas

Code:

415 string addition

Question requirements

Problem-solving ideas

Code:


338-bit bit count

Topic requirements:

Connection:338. Bit Count - LeetCode

Give you an integer n , for each  in 0 <= i <= n , calculate its binary representation The number of a>  as the answer.   returns an array of length  i1n + 1ans

Example 1:

Import:n = 2
Output:[0,1,1]
Answer:
0 --> 0
1 --> 1
2 --> 10

Example 2:

Import:n = 5
Output:[0,1,1,2,1,2]
Answer:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101

Problem-solving ideas:

1. Violence and exhaustion

Traverse 1 to n once, and compare the elements inside with the previous 1 bit by bit. If it is equal to 1, it means that the end of the current i is 1, record it with a counter, otherwise it will not be recorded, and then shift it to the right by 1 bit, as shown in the figure :

Code:

public int[] countBits(int n) {
        int[] array = new int[n + 1];
        array[0] = 0;
        for(int i = 1; i <= n; i++) {
            int x = i;
            int count = 0;
            while(x > 0) {
                if((x & 1) == 1) {
                    count++;
                }
                x >>= 1;
            }
            array[i] = count;
        }
        return array;
    }

2. Solve the N&(N - 1) formula

As shown in the picture:

Explanation:If we find the number of binary 1's in 21, then we can find the number of binary 1's in 20 + 1, and find the number of binary 1's in 20. We can find the number of binary 1s of 16 + 1. If we find the number of binary 1s of 16, we can find the number of binary 1s of 0 + 1. Therefore, we get to find a certain number The number of binary ones of N:(N &(N - 1)) + 1

Code:

public int[] countBits(int n) {
        int[] array = new int[n + 1];
        array[0] = 0;
        for(int i = 1; i < array.length; i++) {
            array[i] = array[i & (i-1)] + 1;
        }
        return array;
    }

3. Solution to the properties of odd and even numbers:

As shown in the picture:

When i = 5 or 7, it is an odd number. Looking at the picture above, we can find that the number of binary 1s in them is the number of binary 1s in the previous subscript 4 and 5 of i + 1.

So when i is an odd number, we just calculate the binary number of its previous subscript + 1.

We can find that when i is an even number, the number of binary 1s they have is the same as the number of binary 1s if i is shifted one position to the right (or divided by 2).

So when i is an even number, we just calculate the number of binary 1 by shifting it to the right by one position.

Code:

public int[] countBits(int n) {
        int[] arr = new int[n + 1];
        arr[0] = 0;
        for(int i = 1; i < arr.length; i++) {
            arr[i] = (i & 1) == 1 ? arr[i - 1] + 1 : arr[i >> 1];
        }
        return arr;
    }

20 valid brackets

Topic requirements:

Connect:LeetCode official website - the technology growth platform loved by geeks around the world

Given a program that only includes '(', ')', '{', '}', '[', ']' string s , determine whether the string is valid.

A valid string must satisfy:

  1. The opening bracket must be closed by a closing bracket of the same type.
  2. Opening brackets must be closed in the correct order.
  3. Every right bracket has a corresponding left bracket of the same type.

Example 1:

输入:s = "()"
输出:true

Example 2:

输入:s = "()[]{}"
输出:true

Example 3:

Import:s = "(]"
Output:false

Problem-solving ideas

Using the data structure of the stack, compare whether the left bracket of the previous bracket matches the current right bracket, and use the first-in, last-out feature of the stack. When a left bracket is encountered, a right bracket is put into the stack, and the characters obtained When it is a right bracket, it is judged whether the right bracket is equal to the top element of the stack. If not, it returns false. If it is equal, it pops up and continues to the next judgment. The string has not been traversed completely. If the stack is empty, there are too many right brackets and false is returned. If the string has been traversed but the stack is not empty, it means there are too many left brackets and false is returned.

Code:

public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for(char x : s.toCharArray()) {
            if(x == '(') {
                stack.push(')');
            } else if(x == '[') {
                stack.push(']');
            } else if(x == '{') {
                stack.push('}');
            } else if(stack.empty() || stack.pop() != x) {
                return false;
            }
        }
        return stack.empty();
    }

415 string addition

Question requirements

Connection:415. String addition - LeetCode

Given two non-negative integers in string form num1 and num2 , calculate their sum and return it also in string form.

You cannot use any of the built-in libraries for handling large integers (such as BigInteger), nor can you directly convert the input string to integer form.

Example 1:

Input:num1 = "11", num2 = "123"
Output: "134"

Example 2:

Input:num1 = "456", num2 = "77"
Output:"533"

Example 3:

Input:num1 = "0", num2 = "0"
Output: "0"

hint:

  • 1 <= num1.length, num2.length <= 104
  • num1 Both and num2 contain only numbers 0-9
  • num1 Neither nornum2 contain any leading zeros

Problem-solving ideas

To add two string numbers, put them into the string, and return the string type, you need to take out the two strings separately, and then find the length of the two strings - 1, which is defined as the subscript , traverse from back to front (arr.length()), traverse them at the same time, take out the current subscript character each time, and then subtract the '0' subscript character from the current subscript character, that is This character is an integer number. The ASCLL table is as shown in the figure.

Then define a carry traversal carry, get the two-character number of the current subscript (x + y + carry), define a StringBuilder type, put (x + y + carry) into this class, and then add % 10 to the carry.

carry = (x + y +carry)/10, each time the subscript is traversed, the above operation must be performed. When the string is traversed, the string is reversed and the string is returned.

Code:

public String addStrings(String num1, String num2) {
        StringBuilder sb = new StringBuilder();
        //记录进位的变量
        int carry = 0;
        //记录字符串的下标
        int n1 = num1.length() - 1;
        int n2 = num2.length() - 1;
        for(; n1 >= 0 || n2 >= 0 || carry != 0; n1--, n2--) {
            int c1 = (n1 < 0) ? 0 : (num1.charAt(n1) - '0');
            int c2 = (n2 < 0) ? 0 : (num2.charAt(n2) - '0');
            sb.append((c1 + c2 + carry) % 10);
            carry = (c1 + c2 + carry) / 10;
        }
        //翻转字符串
        return sb.reverse().toString();
    }

Guess you like

Origin blog.csdn.net/cool_tao6/article/details/134424207