【Java】 牛客网华为机试108题汇总


文章目录

目录

目录

1、求字符串最后一个单词长度

2、计算字符串个数

3、明明的随机数

4、字符串分割

5、进制转换

6、质数因子

7、HJ19 简单错误记录

8、HJ25 数据分类处理

9 HJ30 字符串合并处理



1、求字符串最后一个单词长度


计算字符串最后一个单词的长度,单词以空格隔开。

import java.util.Scanner;

/**
 * @Author: Stephen
 * @Date: 2020/3/21 13:24
 * @Content: 计算字符串最后一个单词的长度,单词以空格隔开。
 */
public class StrLength01 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        while (input.hasNext()){
            String[] str = input.nextLine().split(" ",-1);
            System.out.println(str[str.length-1].length());
        }
    }
}


2、计算字符串个数


写出一个程序,接受一个由字母和数字组成的字符串,和一个字符,
然后输出输入字符串中含有该字符的个数。不区分大小写。

import java.util.Scanner;

/**
 * @Author: Stephen
 * @Date: 2020/3/21 14:17
 * @Content: 写出一个程序,接受一个由字母和数字组成的字符串,和一个字符,
 * 然后输出输入字符串中含有该字符的个数。不区分大小写。
 */
public class WordCount {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String str = input.nextLine();
        String cha = input.nextLine();
        int count = 0;
        if (str != null && str.length()>0){
            for (int i=0;i<str.length();i++){
                if (cha.toLowerCase().charAt(0)==str.toLowerCase().charAt(i)){
                    count++;
                }
            }
        }
        System.out.println(count);
    }
}



3、明明的随机数


明明想在学校中请一些同学一起做一项问卷调查,为了实验的客观性,他先用计算机生成了N个1到1000之间的随机整数(N≤1000),
对于其中重复的数字,只保留一个,把其余相同的数去掉,不同的数对应着不同的学生的学号。
然后再把这些数从小到大排序,按照排好的顺序去找同学做调查。
请你协助明明完成“去重”与“排序”的工作(同一个测试用例里可能会有多组数据,希望大家能正确处理)。

方法一:arrayList+Collections

import java.util.*;

/**
 * @Author: Stephen
 * @Date: 2020/3/21 14:45
 * @Content:
 * 明明想在学校中请一些同学一起做一项问卷调查,为了实验的客观性,他先用计算机生成了N个1到1000之间的随机整数(N≤1000),
 * 对于其中重复的数字,只保留一个,把其余相同的数去掉,不同的数对应着不同的学生的学号。
 * 然后再把这些数从小到大排序,按照排好的顺序去找同学做调查。
 * 请你协助明明完成“去重”与“排序”的工作(同一个测试用例里可能会有多组数据,希望大家能正确处理)。
 */
public class RandomTest {
    public static void main(String[] args) {
         Scanner num = new Scanner(System.in);
        while (num.hasNext()){
            int number = num.nextInt();
            Set<Integer> numbers = new HashSet<Integer>();
            List<Integer> list = new ArrayList<Integer>();
            for (int i =0;i<number;i++){
                // 曲解了题意误以为随机输入是用随机数输入
//            Random rand = new Random();
//            int a=rand.nextInt(1001);
                numbers.add(num.nextInt());
            }
            for (int a:numbers){
                list.add(a);
            }
            Collections.sort(list);
            for (int a:list){
                Systems.out,println(a);
            }
        }
    }
}


方法二:treeset 去重
写的时候是用hashset去重再转arrayList排序,经阅读代码补充使用treeset直接去重排序treeset详解

import java.util.*;
public class RandomTest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){

            int num = sc.nextInt();
            TreeSet<Integer> set = new TreeSet<Integer>();
            for(int i = 0 ; i < num ;i++){
                int curr = sc.nextInt();
                set.add(curr);
            }
            for(Integer i : set){
                System.out.println(i);
            }
        }
    }
}

方法三:Arrays+TreeSet

import java.util.Arrays;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

/**
 * Created by Administrator on 2022/11/29.
 */
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        while (sc.hasNext()) {
            int num = sc.nextInt();
            int[] arr = new int[num];
            //存数组
            for (int i = 0; i < num; i++) {
                arr[i] = sc.nextInt();
            }
            //升序
            Arrays.sort(arr);
            //set自带去重
            Set<Integer> set = new TreeSet<>();
            for (int i = 0; i < num; i++) {
                set.add(arr[i]);
            }
            //遍历输出
            for (Integer integer : set) {
                System.out.println(integer);
            }

        }
    }
}

方法四:有序TreeSet 

import java.util.Scanner;
import java.util.TreeSet;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by Administrator on 2022/11/29.
 */
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        while (sc.hasNext()) {
            int num = sc.nextInt();
            //set自带去重
            Set<Integer> set = new TreeSet<>();
            //存数组
            for (int i = 0; i < num; i++) {
                set.add(sc.nextInt());
            }
            //遍历输出
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                Integer element = (Integer) iterator.next();
                System.out.println(element);
            }
        }
    }
}


4、字符串分割


连续输入字符串,请按长度为8拆分每个字符串后输出到新的字符串数组;
长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。

import java.util.Scanner;

/**
 * @Author: Stephen
 * @Date: 2020/3/21 15:38
 * @Content:
 * •连续输入字符串,请按长度为8拆分每个字符串后输出到新的字符串数组;
 * •长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。
 */
public class StrSplit {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        while (input.hasNext()){
            String str = input.nextLine();
            while (str.length()>=8){
                System.out.println(str.substring(0,8));
                str=str.substring(8);
            }
            if (str.length()<8 && str.length()>0){
                str = str+"0000000";
                System.out.println(str.substring(0,8));
            }
        }
    }
}


5、进制转换


写出一个程序,接受一个十六进制的数,输出该数值的十进制表示。(多组同时输入 )

import java.util.Scanner;

/**
 * @Author: Stephen
 * @Date: 2020/3/21 15:57
 * @Content:
 * 写出一个程序,接受一个十六进制的数,输出该数值的十进制表示。(多组同时输入 )
 */
public class SystemTransform {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        while(sc.hasNext()){
            String str = sc.nextLine();
            System.out.println(fun(str.substring(2)));
        }
    }

    public static int fun(String s){
        int n=0;
        int count= 0;
        int temp = 0;
        char ch;

        while(count<s.length())
        {
            ch = s.charAt(s.length()-count-1);
            if(ch>='0'&&ch<='9'){
                temp = ch-'0';
            }else if(ch>='A'&&ch<='Z'){
                temp = ch-'A'+10;
            }else if(ch>='a'&&ch<='z'){
                temp = ch-'a'+10;
            }else{
                break;
            }
            n += temp*Math.pow(16,count);
            count++;
        }

        return n;
    }
}


6、质数因子


输入一个正整数,按照从小到大的顺序输出它的所有质因子(如180的质因子为2 2 3 3 5 )
最后一个数后面也要有空格

package com.njbdqn.services;

import java.util.Scanner;

/**
 * @Author: Stephen
 * @Date: 2020/3/23 21:46
 * @Content:
 * 输入一个正整数,按照从小到大的顺序输出它的所有质因子(如180的质因子为2 2 3 3 5 )
 * 最后一个数后面也要有空格
 */
public class Primefactors {
    public static void main(String[] args) {
        public static void main(String [] args)
        {
            Scanner sc=new Scanner(System.in);
            long params=sc.nextLong();
            if(params<2)
            {
                sc.close();
                return ;
            }
            String result =getResult(params);
            System.out.println(result);
            sc.close();

        }
    }
    public static String getResult(long ulDataInput){
        StringBuilder str=new StringBuilder();
        int index=2;
        while(index<=ulDataInput)
        {
            if(ulDataInput%index==0){
                if(index==ulDataInput){
                    str.append(index).append(" ");
                    break;
                }else{
                    str.append(index).append(" ");
                    ulDataInput=ulDataInput/index;
                }
            }else
            {
                index++;
            }
        }
        return str.toString();
}

7、HJ19 简单错误记录

方法一:HashMap 方式 ,这个位置发生变化,需要借助数组方式保存进入顺序

import java.util.Scanner;
import java.lang.String;
import java.util.HashMap;
import java.util.Arrays;
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        // while (in.hasNextInt()) { // 注意 while 处理多个 case
        //     int a = in.nextInt();
        //     int b = in.nextInt();
        //     System.out.println(a + b);
        // }
        int start=0;
        HashMap<String,Integer> hm=new HashMap<String,Integer> ();
        ArrayList<String> errKeyList = new ArrayList<String>();
        ArrayList<Integer> errValueList = new ArrayList<Integer>();

        // String temp="esdd\\ed";
        // String[] temp2=temp.split("\\\\");
        // System.out.print(temp2.length);
        // System.out.print(temp2[0]);
        // System.out.print(temp2[1]);

        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String a = in.nextLine();
            String[] b =a.split(" ");
            String c2="";
            if (b[0].indexOf("\\")!=-1)     // 有\就截取,没有就原封不动
			    c2 = b[0].substring(b[0].lastIndexOf("\\")+1,b[0].length());
            else
                c2 = b[0];
            start=0;
            if(c2.length()>16){
                start=c2.length()-16;
                c2=c2.substring(start,c2.length());
            }
            String d=c2+" "+b[1];
            Integer pos=hm.get(d);
            if(pos==null){
                hm.put(d,errKeyList.size());
                errKeyList.add(d);
                errValueList.add(1);
            }else{
                errValueList.set(pos,errValueList.get(pos)+1);
            }
        }
        start=0;
        if(errKeyList.size()>8) start=errKeyList.size()-8;
        for(int i=start;i<errKeyList.size();i++){
            String keyString=errKeyList.get(i);
            String[] keyArray=keyString.split(" ");
            System.out.print(keyArray[0]);
            System.out.print(" ");
            System.out.print(keyArray[1]);
            System.out.print(" ");
            System.out.println(errValueList.get(i));
        }
    }
}

方法二:  LinkedHashMap 方式,map 位置不变

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

public class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        Map<String,Integer> map = new LinkedHashMap();
        String tstr = null;
        while((tstr = bf.readLine()) != null && !tstr.equals("")){
            String[] str = tstr.split("\\s+");//空格符隔开
            String fname=str[0].substring(str[0].lastIndexOf("\\") + 1);
            fname = fname.substring(Math.max(fname.length()-16 ,0))+" "+str[1];
            Integer tmp = map.get(fname);
            if(tmp == null)
                map.put(fname,1);
            else
                map.put(fname, tmp+1);
        }
        int count = 0;
        //遍历map,entrySet()返回了 HashMap 中所有映射项的一个 set 集合视图
        for(Map.Entry<String,Integer> it : map.entrySet()){
            if(map.size() - count <= 8)
                System.out.println(it.getKey()+" "+it.getValue());
            count++;
        }
    }
}

8、HJ25 数据分类处理

方法一:treeset(是小到大有序的)+indexof(或contains,包含字串)

import java.util.Scanner;
import java.lang.String;
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        // while (in.hasNextInt()) { // 注意 while 处理多个 case
        //     int a = in.nextInt();
        //     int b = in.nextInt();
        //     System.out.println(a + b);
        // }
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String I = in.nextLine();
            String[] I2=I.split(" ");
            int i=0;
            String R = in.nextLine();
            String[] R2=R.split(" ");
            TreeSet<Integer> ts=new TreeSet<Integer>();
            for(i=1;i<R2.length;i++){
                ts.add(Integer.parseInt(R2[i]));
            }
            Iterator iter=ts.iterator();
            int count2=0;
            ArrayList<Integer> rs=new ArrayList<Integer>();

            for(i=0;i<ts.size();i++){
                Integer strTempi1=(Integer)iter.next();
                String strTempi=Integer.toString(strTempi1);
                // System.out.println(strTempi);
                int equitcont=0;
                for(int j=1;j<I2.length;j++){
                    if(I2[j].contains(strTempi)){
                        equitcont++;
                        if(equitcont==1){
                            rs.add(Integer.parseInt(strTempi));
                            rs.add(equitcont);
                            count2=rs.size();
                        }
                        rs.set(count2-1,equitcont);
                        rs.add(j-1);
                        rs.add(Integer.parseInt(I2[j]));
                    }
                   
                }
            }

            if(rs.size()>0){
                System.out.print(rs.size());
                System.out.print(" ");
                for(i=0;i<rs.size();i++){
                    System.out.print(rs.get(i));
                    System.out.print(" ");
                }
            }
            

        }


    }
}

方法二:Arrays.sort函数 ++indexof(或contains,包含字串)

import java.util.Scanner;
import java.lang.String;
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        // while (in.hasNextInt()) { // 注意 while 处理多个 case
        //     int a = in.nextInt();
        //     int b = in.nextInt();
        //     System.out.println(a + b);
        // }
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String I = in.nextLine();
            String[] I2=I.split(" ");
            int i=0;
            String R = in.nextLine();
            String[] R2=R.split(" ");
            int[] R1=new int[R2.length-1];
            for(i=1;i<R2.length;i++){
                R1[i-1]=Integer.parseInt(R2[i]);
            }
            Arrays.sort(R1);
            int count2=0;
            ArrayList<Integer> rs=new ArrayList<Integer>();

            for(i=0;i<R1.length;i++){
                if(i>0 && R1[i-1]==R1[i]) continue;
                String strTempi=Integer.toString(R1[i]);
                int equitcont=0;
                for(int j=1;j<I2.length;j++){
                    if(I2[j].contains(strTempi)){
                        equitcont++;
                        if(equitcont==1){
                            rs.add(Integer.parseInt(strTempi));
                            rs.add(equitcont);
                            count2=rs.size();
                        }
                        rs.set(count2-1,equitcont);
                        rs.add(j-1);
                        rs.add(Integer.parseInt(I2[j]));
                    }
                   
                }
            }

            if(rs.size()>0){
                System.out.print(rs.size());
                System.out.print(" ");
                for(i=0;i<rs.size();i++){
                    System.out.print(rs.get(i));
                    System.out.print(" ");
                }
            }
            

        }


    }
}

9 HJ30 字符串合并处理

方法一:自己编写

import java.util.Scanner;
import java.lang.String;
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        // while (in.hasNextInt()) { // 注意 while 处理多个 case
        //     int a = in.nextInt();
        //     int b = in.nextInt();
        //     System.out.println(a + b);
        // }
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String a = in.nextLine();
            String c = a.replace(" ", "");
            char[] d = new char[c.length() / 2];
            if (c.length() % 2 == 1) d = new char[(c.length() + 1) / 2];
            char[] e = new char[c.length() / 2];
            char[] f = c.toCharArray();
            int i = 0;
            for (i = 0; i < f.length; i++) {
                if (i % 2 == 0)
                    d[i / 2] = f[i];
                else {
                    e[i / 2] = f[i];
                    // System.out.println(i/2);
                }

            }
            Arrays.sort(d);
            Arrays.sort(e);
            HashMap<Character, Character> map = new HashMap<Character, Character>();
            map.put('0', '0');
            map.put('1', '8');
            map.put('2', '4');
            map.put('3', 'C');
            map.put('4', '2');
            map.put('5', 'A');
            map.put('6', '6');
            map.put('7', 'E');
            map.put('8', '1');
            map.put('9', '9');
            map.put('a', '5');
            map.put('b', 'D');
            map.put('c', '3');
            map.put('d', 'B');
            map.put('e', '7');
            map.put('f', 'F');
            map.put('A', '5');
            map.put('B', 'D');
            map.put('C', '3');
            map.put('D', 'B');
            map.put('E', '7');
            map.put('F', 'F');
            for (i = 0; i < d.length; i++) {
                if(map.get(d[i])!=null){
                    d[i] = map.get(d[i]);
                } 
            }
            
            for (i = 0; i < e.length; i++) {
                if(map.get(e[i])!=null)
                    e[i] = map.get(e[i]);
            }
            for (i = 0; i < d.length; i++) {
                System.out.print(d[i]);
                if (i < e.length) System.out.print(e[i]);
            }
            ;
        }
    }
}

方法二:网上收集,采用 StringBuilder.reverse() 方法

package nowcoder.x3x;

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

public class HJ030 {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = br.readLine();
        // 合并第一步
        String m = line.replace(" ", "");

        char[] chars = m.toCharArray();
        // 第二步 偶数位
        for (int i = 0; i < chars.length; i = i + 2) {
            for (int j = 0; j < chars.length - 2; j = j + 2) {
                if (chars[j] > chars[j + 2]) {
                    char temp = chars[j];
                    chars[j] = chars[j + 2];
                    chars[j + 2] = temp;
                }
            }
        }

        // 第二步 奇数位
        for (int i = 1; i < chars.length; i = i + 2) {
            for (int j = 1; j < chars.length - 2; j = j + 2) {
                if (chars[j] > chars[j + 2]) {
                    char temp = chars[j];
                    chars[j] = chars[j + 2];
                    chars[j + 2] = temp;
                }
            }
        }

        // 第三步 转换
        StringBuilder stringBuilder = new StringBuilder();
        for (char c : chars) {
            if ((c >= '0' && c <= '9')
                    || (c >= 'A' && c <= 'F')
                    || (c >= 'a' && c <= 'f')
            ) {
                StringBuilder binaryString = new StringBuilder(Integer.toBinaryString(Integer.parseInt(String.valueOf(c), 16)));
                int len = binaryString.length();
                if (len < 4) {
                    for (int i = 0; i < 4 - len; i++) {
                        binaryString.insert(0, "0");
                    }
                }
                binaryString.reverse();
                int y = Integer.parseInt(binaryString.toString(), 2);
                stringBuilder.append(Integer.toHexString(y).toUpperCase());
            } else {
                stringBuilder.append(c);
            }
        }
        System.out.println(stringBuilder);
    }
}

9、HJ39 判断两个IP是否属于同一子网

方法一:作者编写

import java.util.Scanner;
import java.util.*;
import java.lang.*;


// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    // public static String fill(String a){
    //     String b="";
    //     for (int i=0;i<8-a.length();i++){
    //             b="0"+b;
    //     }
    //     return b;
    // }
    public static boolean isMaskError (String[] ip){
        String[] b={"","","",""};
        boolean result=false;
        for (int i=0;i<4;i++){
            b[i]=Integer.toBinaryString(Integer.valueOf(ip[i]));
            // fill
            if(b[i].length()<8){
                for(int j=0;j<8-b[i].length();j++){
                    b[i]="0"+b[i];
                }
            }
           
        }
        String link=b[0]+b[1]+b[2]+b[3];
        if(b[0].charAt(0)=='0') return true;
        if(link.contains("01")) result=true;
        return result;
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        // while (in.hasNextInt()) { // 注意 while 处理多个 case
        //     int a = in.nextInt();
        //     int b = in.nextInt();
        //     System.out.println(a + b);
        // }
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String[] a1=in.nextLine().split("\\.");
            String[] a2= in.nextLine().split("\\.");
            String[] a3 = in.nextLine().split("\\.");
            if(isMaskError(a1)) {
                System.out.println(1);
                continue;
            }
            int[] b1=new int[4];
            int[] b2=new int[4]; 
            int[] b3=new int[4];   
            int[] c1=new int[4];
            int[] c2=new int[4]; 
            int[] d1=new int[4];
            // String[] d2=new String[4];  
            int i=0;
            boolean isequit=true;
            boolean errorip=false;
            for(i=0;i<4;i++){
                b1[i]=Integer.parseInt(a1[i]);
                b2[i]=Integer.parseInt(a2[i]);
                b3[i]=Integer.parseInt(a3[i]);
                // ip or mask error 
                if(!(b1[i]>=0 && b1[i]<256 && b2[i]>=0 && b2[i]<256 && b3[i]>=0 && b3[i]<256)){
                    errorip=true;
                    break;
                }
                c1[i]=b1[i]&b2[i];
                c2[i]=b1[i]&b3[i];
                if(c1[i]!=c2[i]) isequit=false;
            }
            // is 0 not 2 error 1
            if(errorip) {
                System.out.println(1);
                continue;
            }
            // is 0 not 2 error 1
            if(isequit) System.out.println(0); else System.out.println(2);
          
        }
    }
}

  • 4
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值