leetcode learning summary

Transfer from https://leetcode-cn.com/

1. The sum of two numbers

Given an integer array nums and a target value target, and ask you to identify the target value of the two integers in the array, and return to their array subscript.

You can assume that each input corresponds to only one answer. However, you can not re-use the same array element.

class Solution {
    public static int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        for(int i = 0;i<nums.length;i++){
            for(int j = i+1;j<nums.length;j++){
                int a = nums[i] + nums[j];
                if(target == a){
                  res[0] = i;
                  res[1] = j;
                  break;
return res; } } }
return res; } public static void main(String[] args){ int[] nums = {0,1,2,3,4,5,6}; int target = 4; int[] rest = Solution.twoSum(nums,target); } }

 2. Reverse integer

Gives a 32-bit signed integer, you need this integer number on each inverted. Suppose we have an environment can only store a 32-bit signed integer, then the value range of [-231 231--1]. Please According to this hypothesis, if integer overflow after reverse it returns 0.

class Solution {
    public int reverse(int x) {
        long temp = 0;
       
        while(x != 0){
            int pop = x % 10;
            temp = temp * 10 + pop;
            
            if(temp > Integer.MAX_VALUE || temp < Integer.MIN_VALUE){
                return 0;
            }
            x /= 10;
        }
        return (int)temp;
    }
}

 

Guess you like

Origin www.cnblogs.com/wwmiert/p/11026680.html
Recommended