牛客网华为机试java版

HJ1 字符串最后一个单词的长度

在这里插入图片描述
方法1:用时20ms

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        if(s.length() > 5000)return;
        Integer index = s.lastIndexOf(" ");
        String word = s.substring(index+1);
        System.out.print(word.length());
    }
}

方法2:用时8ms

import java.util.Scanner;
import java.io.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) throws IOException{
        InputStream inputStream = System.in ;
        int length=0;
        char c;
        while('\n' != (c=(char)inputStream.read())){
            length ++ ;
            if(c == ' '){
                length = 0;
            }
        }
        System.out.println(length);
    }
}

HJ2 计算某字符出现次数

在这里插入图片描述
方法1:用时30ms

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        // Scanner in = new Scanner(System.in);
        // String first = in.nextLine();
        // char second = in.next().charAt(0);
        // int times = 0;
        // for(int i=0;i<first.length();i++){
        //     char te = first.charAt(i);
        //     if(second == te || second == te - 32 || second == te+32){
        //         times++;
        //     }
        // }
        // System.out.print(times);

        Scanner in = new Scanner(System.in);
        String s = in.nextLine().toLowerCase();
        String b = in.nextLine().toLowerCase();
        System.out.println(s.length() - s.replaceAll(b, "").length());
    }
}

方法2:用时6ms

import java.io.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) throws IOException {
        int count = 0;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        char[] first = bufferedReader.readLine().toLowerCase().toCharArray();
        char[] second = bufferedReader.readLine().toLowerCase().toCharArray();
        char tar = second[0];
        for(char c : first){
            if(c == tar){
                count++;
            }
        }
        System.out.print(count);
    }
}

HJ3 明明的随机数

在这里插入图片描述

方法1:用时10ms

import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferReader = new BufferedReader(new InputStreamReader(
                System.in));
        Integer n = Integer.parseInt(bufferReader.readLine());
        HashMap<String, String> hashMap = new HashMap<String, String>();

        for (int i = 0; i < n; i++) {
            String str = bufferReader.readLine();
            if (str != null) {
                if (!hashMap.containsKey(str)) {
                    hashMap.put(str, "");
                }
            }
        }
        Object[] keyArray = hashMap.keySet().toArray();
        Integer[] list = new Integer[keyArray.length];
        for (int i = 0; i < keyArray.length; i++) {
            list[i] = Integer.parseInt(keyArray[i].toString());
        }
        Arrays.sort(list);
        for (int i : list) {
            System.out.println(i);
        }
    }
}

方法2:用时8ms

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

	public static void main(String[] args) throws IOException {
		
		BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
		String str;
		while((str=bf.readLine())!=null)
		{
            
			boolean[] stu=new boolean[1001];
			StringBuilder sb=new StringBuilder();
			int n=Integer.parseInt(str);
			for(int i=0;i<n;i++)
				stu[Integer.parseInt(bf.readLine())]=true;
			for(int i=0;i<1001;i++)
				if(stu[i])
					sb.append(i).append("\n");
			sb.deleteCharAt(sb.length()-1);
			System.out.println(sb.toString());
		}
	}
}

HJ4 字符串分隔

在这里插入图片描述
方法1:用时9ms

import java.io.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
        String str = bufferReader.readLine();
        int length = str.length();
        if((length % 8)<8 && (length % 8)!=0){
            int n = 8-(length % 8);
            for(int i=0;i<n;i++){
                str+="0";
            }
           
        }
        char[] arr = str.toCharArray();
        String temp = "";
        for(int i=0;i<arr.length;i++){
            temp+=arr[i];
            if((i+1)%8 == 0){
                System.out.println(temp);
                temp = "";
            }
        }
    }
}

方法2:用时6ms

import java.io.*;

public class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str;
        while((str = br.readLine())!=null){
            int len = str.length();
            int start = 0;
            while (len >= 8){
                System.out.println(str.substring(start, start + 8));
                start += 8;
                len -= 8;
            }
            if (len > 0) {
                char[] tmp = new char[8];
                for(int i = 0;i<8;i++){
                    tmp[i]='0';
                }
                for(int i = 0; start < str.length(); i++) {
                    tmp[i] = str.charAt(start++);
                }
                System.out.println(String.valueOf(tmp));
            }
        }
    }
}

HJ5 进制转换

方法1:用时9ms

import java.io.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
        String str = bufferReader.readLine();
        if(str.startsWith("0x")){
            Long n = Long.parseLong(str.substring(2),16);
            System.out.println(n);
        }else{
            Long n = Long.parseLong(str,16);
            System.out.println(n);
        }
    }
}

方法2:用时5ms

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
    public static void main(String[] args) throws IOException {

        // 先读取控制台输入
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String str;

        char[] num_arr =new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

        while (null != (str = reader.readLine())) {
            // 取出 0x 后面的字符串
            String hexNum = str.substring(2);
            // 字符串长度,可以用来表示位数
            int digit = hexNum.length();
            // 存放十进制结果
            int result = 0;
            for (int i = 0; i < digit; i++) {
                char cur_char = hexNum.charAt(i);
                int cur_num = indexOf(num_arr, cur_char);
                result += cur_num * Math.pow(16, digit - i - 1);
            }
            System.out.println(result);
        }
    }

    public static int indexOf(char[] arr, char num) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == num) {
                return i;
            }
        }
        return 0;
    }
    
}

HJ6 质数因子

在这里插入图片描述
方法1:用时10ms

import java.io.*;

import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) throws IOException{
        BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
        String str = bufferReader.readLine();
        Integer num = Integer.parseInt(str);
        printPrimeFactors(num);

    }
    public static void printPrimeFactors(int number) {
        while(number % 2 == 0){
            System.out.print(2+" ");
            number /= 2;
        }
        for(int i=3;i<=Math.sqrt(number);i+=2){
            while(number % i == 0){
                System.out.print(i+" ");
                number /= i;
            }
        }
        if(number>2){
            System.out.print(number);
        }

    }
}

方法2:用时6ms

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str;
        while ((str = br.readLine()) != null) {
            int num = Integer.parseInt(str);
            StringBuilder sb = new StringBuilder();
            for (int i = 2; i <= Math.sqrt(num); i++) {
                if (num % i == 0) {
                    sb.append(i).append(" ");
                    num = num / i;
                    i--;
                }
            }
            sb.append(num).append(" ");
            System.out.println(sb.toString());
        }
    }
}

HJ7 取近似值

在这里插入图片描述
方法1:用时8ms

import java.io.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.
        in));
        String str = bufferReader.readLine();        
        double num = Double.parseDouble(str);
        int res = (int)num;
        if(num-res >= 0.5){
            System.out.println(res+1);
        }else{
            System.out.println(res);
        }

    }
}

方法2:用时9ms

import java.util.*;
import java.io.*;
public class Main {
    public static void main(String args[])throws Exception{
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String str = bf.readLine();
        int index = str.indexOf(".");
        int a = Integer.parseInt(str.substring(0, index));
        int b = Integer.parseInt(str.substring(index + 1, index + 2));
        if(b >= 5){
            a++;
            System.out.println(a);
        }else{
            System.out.println(a);

        }
    }
}

HJ8 合并表记录

在这里插入图片描述
方法1:用时11ms

import java.io.*;
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) throws IOException{
        BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
        String str = bufferReader.readLine();
        int num = Integer.parseInt(str);
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        while((str = bufferReader.readLine())!= null){
            String[] arr = str.split(" ");
            Integer key = Integer.parseInt(arr[0]);
            Integer value = Integer.parseInt(arr[1]);
            if(!map.containsKey(key)){
                map.put(key,value);
            }else{
                map.put(key,map.get(key)+value);
            }
        }
        Integer[] keys = map.keySet().toArray(new Integer[0]);
        Arrays.sort(keys);
        for(Integer i : keys){
            System.out.println(i+" "+map.get(i));
        }
    }
}

方法2:用时8ms

import java.util.*;
import java.io.*;
public class Main {
    public static void main(String[] args) throws Exception{
         StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        st.nextToken();      // 分隔符
        int n = (int) st.nval;   // 强转
        int[] arr = new int[n];
 
        for (int i = 0; i < n; i++) {
            st.nextToken();
            int key = (int) st.nval;
            st.nextToken();
            int value = (int) st.nval;
            arr[key] = arr[key] + value;
        }
 
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < arr.length ; i++) {
            if(arr[i] != 0){
                sb.append(i).append(" ").append(arr[i]).append("\n");
            }
        }
        System.out.println(sb.toString());
    }
}

题目貌似没说key是连续的,可以使用TreeMap代替普通的数组实现,无非都想要自带的排序效果。

HJ9 提取不重复的整数

方法1:用时10ms

import java.io.*;

import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args)throws IOException {
        BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
        String str = bufferReader.readLine();
        HashMap<Integer,Boolean> map = new HashMap<Integer,Boolean>();
        char[] arr = str.toCharArray();
        for(int i = arr.length-1;i>=0;i--){
            Integer key = Integer.parseInt(arr[i]+"");
            if(!map.containsKey(key)){
                map.put(key,true);
                System.out.print(key);
            }
        }

    }
}

方法2:用时5ms

import java.io.InputStream;

public class Main {

    public static void main(String[] args) throws Exception {
        InputStream in = System.in;
        int available = in.available()-1;
        char[] chars = new char[available];
        while (available-- > 0) {
            chars[available] = (char) in.read();
        }
        StringBuilder resul = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            if (resul.lastIndexOf(String.valueOf(chars[i])) != -1){
                continue;
            }
            resul.append(chars[i]);
        }
          System.out.println(resul.toString());
    }

}

HJ26 字符串排序

在这里插入图片描述
方法1:用时7ms

import java.util.*;

import java.io.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args)throws IOException {
        BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
        String str = bufferReader.readLine();
        StringBuilder sb = new StringBuilder();
        for (int j = 0; j < str.length(); j++) {
            char ch = str.charAt(j);
            if ((ch >= 65 && ch <=90) || (ch >= 97 && ch <= 122)) {
                sb.append('0');
            } else {
                sb.append(ch);
            }

        }
        for (int i = 65; i < 97; i++) {
            int m = 0;
            for (int j = 0; j < str.length(); j++) {
                char ch = str.charAt(j);
                char nch = sb.charAt(m);
                if (ch == i || ch == i + 32) {
                    if (nch == '0') {
                        sb.setCharAt(m, ch);
                        while(m<str.length()){
                            m++;
                            nch = sb.charAt(m);
                            if(nch == '0'){
                                break;
                            }
                        }
                    } else {
                        int n = m + 1;
                        while (n < str.length()) {
                            nch = sb.charAt(n);
                            if (nch == '0') {
                                sb.setCharAt(n, ch);
                                m++;
                                break;
                            }
                            n++;
                        }
                    }


                }
            }
        }
        System.out.print(sb.toString());

    }
}

方法2:用时6ms

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s;
        while((s = br.readLine()) != null){
            char[] ch = s.toCharArray();
            char[] chars = new char[ch.length];
            int flag = 65, j=0;
            while(flag<=90){
                for(int i=0; i<ch.length; i++){
                    if((ch[i]>=65&&ch[i]<=90) || (ch[i]>=97&&ch[i]<=122)){
                        if(ch[i]==flag || ch[i]== flag+32){
                            chars[j] = ch[i];
                            j++;
                        }
                    }
                }
                flag++;
            }
            
            j=0;
            for(int i=0; i<ch.length; i++){
                 if((ch[i]>=65&&ch[i]<=90) || (ch[i]>=97&&ch[i]<=122)){
                     ch[i] = chars[j];
                     j++;
                 }
            }
            System.out.println(String.valueOf(ch));
        }
    }
}

HJ80 整型数组合并

在这里插入图片描述
方法1:用时10ms

import java.util.*; 

import java.io.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) throws IOException{
        BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
        Integer first = Integer.parseInt(bufferReader.readLine());
        Integer[] firstArr = new Integer[first];
        String[] firstStrArr = bufferReader.readLine().split(" ");
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int i=0;i<first;i++){
            firstArr[i] = Integer.parseInt(firstStrArr[i]);
            if(!map.containsKey(firstArr[i])){
                map.put(firstArr[i],0);
            }
            
        }
        Integer second = Integer.parseInt(bufferReader.readLine());
        Integer[] secondArr = new Integer[second];
        String[] secondStrArr = bufferReader.readLine().split(" ");
        for(int i=0;i<second;i++){
            secondArr[i] = Integer.parseInt(secondStrArr[i]);
           if(!map.containsKey(secondArr[i])){
                map.put(secondArr[i],0);
            }
        }
        Integer[] res = map.keySet().toArray(new Integer[0]);
        Arrays.sort(res);
        for(Integer i:res){
            System.out.print(i);
        }
       
    }
}

方法2:用时9ms

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
  
public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line;
        while ((line = br.readLine()) != null && line.length() > 0) {
            String[] strs = br.readLine().split(" ");
            int[] array1 = new int[strs.length];
            for (int i = 0; i < array1.length; ++i)
                array1[i] = Integer.parseInt(strs[i]);
  
            line = br.readLine();
            strs = br.readLine().split(" ");
            int[] array2 = new int[strs.length];
            for (int i = 0; i < array2.length; ++i)
                array2[i] = Integer.parseInt(strs[i]);
  
            System.out.println(combineBySort(array1, array2));
  
        }
    }
  
    static String combineBySort(int[] array1, int[] array2) {
        int[] outPut = new int[array1.length + array2.length];
        Arrays.sort(array1);
        Arrays.sort(array2);
  
        int M = array1.length, R = array2.length;
        int idx = 0, i = 0, j = 0;
        if (array1[i] > array2[j]) {
            outPut[idx++] = array2[j++];
        } else if (array1[i] < array2[j]) {
            outPut[idx++] = array1[i++];
        } else {
            outPut[idx++] = array1[i++];
            j++;
        }
        while (i < M && j < R) {
            if (array1[i] > array2[j]) {
                if (outPut[idx - 1] != array2[j])
                    outPut[idx++] = array2[j];
                ++j;
            } else if (array1[i] < array2[j]) {
                if (outPut[idx - 1] != array1[i])
                    outPut[idx++] = array1[i];
                ++i;
            } else {
                if (outPut[idx - 1] != array1[i])
                    outPut[idx++] = array1[i];
                ++i;
                ++j;
            }
        }
  
        if (i == M) {
            while( j < R){
                if (outPut[idx - 1] != array2[j])//去重
                    outPut[idx++] = array2[j];
                j++;
            }
                
        } else {
            for (; i < M; ++i)
                if (outPut[idx - 1] != array1[i])
                    outPut[idx++] = array1[i];
        }
  
        StringBuilder sb = new StringBuilder();
        for (i = 0; i < idx; ++i)
            sb.append(outPut[i]);
  
        return sb.toString();
    }
  
}

HJ101 输入整型数组和排序标识,对其元素按照升序或降序进行排序

在这里插入图片描述
方法1:用时11ms

import java.util.*;

import java.io.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args)throws IOException {
        BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
        Integer sum = Integer.parseInt(bufferReader.readLine());
        Integer[] arrInt = new Integer[sum];
        String[] arrStr = bufferReader.readLine().split(" ");
        for(int i=0;i<arrInt.length;i++){
            arrInt[i] = Integer.parseInt(arrStr[i]);
        }
        Integer sort = Integer.parseInt(bufferReader.readLine());
        Arrays.sort(arrInt);
        if(sort == 0){
            for(int i =0;i<arrInt.length;i++){
                System.out.print(arrInt[i]+" ");
            }
        }else{
            for(int i =arrInt.length-1;i>=0;i--){
                System.out.print(arrInt[i]+" ");
            }
        }
    }
}

方法2:用时13ms

/**
 * @FileName: Test
 * @Author: KipFcrs
 * @Date: 2020/8/3 16:27
 */

import java.util.*;
import java.io.*;

public class Main {

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String inputCount;

        while ((inputCount = br.readLine()) != null) {
            int count = Integer.parseInt(inputCount);
            String[] input = br.readLine().split(" ");
            int flag = Integer.parseInt(br.readLine());
            int[] num = new int[input.length];
            for (int i = 0; i < input.length; i++) {
                num[i] = Integer.parseInt(input[i]);
            }
            quickSort(num,0,num.length - 1);
            StringBuilder sb = new StringBuilder();
            if(flag == 0){
                for (int j = 0; j < num.length; j++) {
                    sb.append(num[j]).append(" ");
                }
            }else{
                for (int k = num.length - 1; k >= 0; k--) {
                    sb.append(num[k]).append(" ");
                }
            }
            System.out.println(sb.substring(0,sb.length()-1));
        }

    }

    public static void quickSort(int[] num, int L, int R) {
        if (L >= R) {
            return;
        }
        int p = partition(num, L, R);
        quickSort(num, L, p - 1);
        quickSort(num, p+1, R);
    }

    public static int partition(int[] num, int L, int R) {
        int key = num[L];
        int pivot = L;

        for (int i = L + 1; i <= R; i++) {
            if (num[i] < key) {
                int temp = num[++pivot];
                num[pivot] = num[i];
                num[i] = temp;
            }
        }
        int tt = num[pivot];
        num[pivot] = num [L];
        num[L] = tt;
        return pivot;
    }

}

  • 15
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
根据引用,牛客网华为机试解的JavaScript本提供了第11到20的解答。其中包括了数字颠倒、字符串反转、句子逆序、字符串排序、求int型数据在内存中存储时1的个数、购物单、坐标移动、识别有效的IP地址和掩码并进行分类统计、简单错误记录和密码验证合格程序。 根据引用,目描述了如何将输入的整数以字符串的形式逆序输出。程序不考虑负数的情况,如果数字中包含0,逆序形式也会包含0。 根据引用,目描述了如何计算输入的正整数在内存中存储时1的个数。目要求输入一个整数(int类型),并将该数转换成二进制形式后输出其中1的个数。 需要注意的是,输入和输出的具体实现可能因目而异,以上引用提供了一些示例代码,但并不代表所有目的通用解法。正确的输入输出取决于具体目的要求和所给代码的实现方式。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [JavsScript牛客网华为机试(11-20)解](https://blog.csdn.net/weixin_43465339/article/details/110709521)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AIGIS.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值