HJ5 base conversion, NC61 sum of two numbers, HJ3 obvious random number

HJ5 hexadecimal conversion

Title Description
Write a program that accepts a hexadecimal number and outputs the decimal representation of the value.

Input Description:
Enter a hexadecimal value string.
Output description:
Output the decimal string of the value. Different groups of test cases are separated by \n.

Example 1
Input:
0xAA
Output:
170

It’s been a long time since I did a programming question, and I feel like I’m back when I first started learning, the Java API is too powerful and all-encompassing;

Pass answer one: use JavaAPI Integer.valueOf(xx, base);

    public static void main(String[] args) {
    
    

        while(in.hasNextLine()) {
    
    
            String input = in.nextLine();
            String target = input.substring(2);
            Integer valueOf = Integer.valueOf(target, 16);
            System.out.println(valueOf);
        }
    }

Pass answer two:

  1. Remove the two characters of 0x to obtain the remaining string target;
  2. Traversing from back to front, the last position is target.length() - 1, and the corresponding index pow is 0;
  3. If the value of the position is '0' - '9', subtract '0' to get the real value of the position;
  4. If the value of the position is 'A' -'F', subtract 'A' and add 10 to get the real value of the position;
  5. Traversing the penultimate position is target.length() - 2, the corresponding base index is 1; repeat steps 3 and 4;
  6. finally get the result;
    public static void main(String[] args) {
    
    
        Scanner in = new Scanner(System.in);

        while(in.hasNextLine()) {
    
    
            String input = in.nextLine();
            String target = input.substring(2);
            double finalVal = 0;
            int pow = 0;
            for(int index = target.length() - 1; index >= 0; index --) {
    
    
                char indexVal = target.charAt(index);
                int temp = 0;
                if(indexVal >= '0' && indexVal <= '9') {
    
    
                    temp = indexVal - '0';
                }else if(indexVal >= 'A' && indexVal <= 'Z') {
    
    
                    temp = indexVal - 'A' + 10;
               }
                finalVal = finalVal + temp * Math.pow(16, pow);
                pow = pow + 1;
            }
            System.out.println(finalVal);
        }
    }

NC61 Sum of two numbers

Description
Given an integer array numbers and a target value target, please find the subscripts of two numbers whose sum is equal to the target value in the array, and the returned subscripts are arranged in ascending order.
(Note: The subscript of the returned array starts from 1, and it is guaranteed that the target can be obtained by adding the two numbers in the array)

Input:
[3,2,4],6
Return value:
[2,3]
Explanation:
Because 2+4=6, the subscript of 2 is 2, and the subscript of 4 is 3, and because the subscript 2 < next Mark 3, so return [2,3]

Method 1: Violently crack
two layers of for loops, add them up to the target value, and return the two indexes;

import java.util.*;
public class Solution {
    
    
    /**
     * 
     * @param numbers int整型一维数组 
     * @param target int整型 
     * @return int整型一维数组
     */
    public int[] twoSum (int[] numbers, int target) {
    
    
        // write code here
        int n = numbers.length;
        int[] res = {
    
    -1, -1};
        //遍历数组
        for (int i = 0; i < n; ++i) {
    
    
            for (int j = i + 1; j < n; ++j) {
    
    
                //判断相加值是否为target
                if (numbers[i] + numbers[j] == target) {
    
    
                    res[0] = i+1;
                    res[1] = j+1;
                    //返回值
                    return res;
                }
            }
        }
        return res;
    }
}

The time complexity of this method is n^2, and if the time complexity is required, a timeout will occur;

Method 2: Use the hash structure
variable beforeIndex: indicates the first coordinate;
variable afterIndex: indicates the second lock table;
there is a relationship: num[beforeIndex] + num[afterIndex] = target;
that is: target - num[afterIndex] = num[beforeIndex];
put num[beforeIndex] into Map, key is num[beforeIndex], val is index coordinate;

process:

  1. Determine whether there is a target - num[afterIndex] index in the Map;
  2. If it does not exist, put target - num[afterIndex] as the key and val as the index coordinate afterIndex into the map;
  3. If it exists, then target - num[afterIndex] is the key, get beforeIndex and return;
    code:
import java.util.*;


public class Solution {
    
    
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param numbers int整型一维数组 
     * @param target int整型 
     * @return int整型一维数组
     */
    public int[] twoSum (int[] numbers, int target) {
    
    
        // write code here
        int left  = 0;
        int right = 0;
        int[] result = {
    
    -1, -1};
        HashMap<Integer, Integer> map = new HashMap<>();
        for(int index = 0; index < numbers.length; index ++) {
    
    
            Integer val = target - numbers[index];
            boolean flag = map.containsKey(val);
            if (flag) {
    
    
               Integer beforeIndex =  map.get(val);
               result[0] = beforeIndex + 1;
               result[1] = index + 1;
               return result;
            }else {
    
    
                map.put(numbers[index], index);
            }

        }
        
        return result;
    }
}

HJ3 Obvious random number

Description
Obviously generate N random integers between 1 and 500. Please delete the repeated numbers, that is, keep only one of the same numbers, remove the rest of the same numbers, and then sort these numbers from small to large, and output them in the order they are arranged.
Data range: 1≤n≤1000, the size of the input number satisfies 1≤val≤500
Input description:
first input the number N of random integers in the first line. Enter an integer in each of the next N lines, representing a random number that is clearly generated. For the specific format, please refer to the "Example" below.

Output description:
Output multiple lines, indicating the result of input data processing

Input:
3
2
2
1
Output:
1
2
Explanation:
Input Explanation:
The first number is 3, that is, N=3 in this small sample, indicating that three random integers between 1 and 500 are generated by computer, then One random number per line, a total of 3 lines, that is, these 3 random numbers are:
2
2
1
, so the output of the sample is:
1
2

Solution 1: Using TreeSet, orderly and non-repetitive, can solve this problem;

import java.util.*;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Scanner sc = new Scanner(System.in);
        //获取个数
        int num = sc.nextInt();
        //创建TreeSet进行去重排序
        TreeSet set = new TreeSet();
        //输入
        for(int i =0 ; i < num ;i++){
    
    
            set.add(sc.nextInt());
        }

        //输出
        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
    
    
            System.out.println(iterator.next());
        }
    }
}

Method 2: Use HashMap to de-duplicate, stream Stream to sort;
I don’t use TreeSet much in my work, most of them use Stream to sort. If I used to work, I would do this; it is limited to java8

        Scanner sc = new Scanner(System.in);
        //获取个数
        int num = sc.nextInt();
        //创建TreeSet进行去重排序
        HashMap<Integer, Integer> map = new HashMap<>();
        //输入
        for(int i =0 ; i < num ;i++){
    
    
            map.put(sc.nextInt(), 1);
        }

        map.keySet().stream().sorted().collect(Collectors.toList()).forEach(val -> System.out.println(val));

Method 3: Use the data size <500, and the number is less than 1000, so you can join an array with a length greater than 1000, and set the value of the corresponding coordinate to 1 every time you input a number; after the input, traverse the array to determine whether the value of the array element
is is 1, if it is 1, print the following table, otherwise skip;
code:

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    
    

    public static void main(String[] args) {
    
    
        Scanner scaner = new Scanner(System.in);
        int count =  scaner.nextInt();
        int[] data = new int[1001];
        for(int index = 1; index <= count; index ++) {
    
    
            int val = scaner.nextInt();
            data[val] = 1;
        }

        for(int index = 0; index < data.length; index++) {
    
    
            if(data[index] == 1) {
    
    
                System.out.println(index);
            }
        }

        scaner.close();
    }
}

personal feeling

The Java API is powerful and all-encompassing. The latter style of writing is more like the practice of programming in sophomores and juniors, and the ability to study programming;

Guess you like

Origin blog.csdn.net/yaoyaochengxian/article/details/131793562