1. 程式人生 > >華為機試程式設計題(三)

華為機試程式設計題(三)

華為機試程式設計題分享又來啦。本次的部分題目也比較簡單,大家自由發揮的餘地也很大哦。好了,廢話不多說,下面就進入正題嘍。

1、座標移動

題目描述

開發一個座標計算工具, A表示向左移動,D表示向右移動,W表示向上移動,S表示向下移動。從(0,0)點開始移動,從輸入字串裡面讀取一些座標,並將最終輸入結果輸出到輸出檔案裡面。

輸入:合法座標為A(或者D或者W或者S) + 數字(兩位以內),座標之間以;分隔。非法座標點需要進行丟棄。如AA10;  A1A;  $%$;  YAD; 等。

下面是一個簡單的例子 如:

A10;S20;W10;D30;X;A1A;B10A11;;A10;

處理過程:起點(0,0)

+   A10   =  (-10,0)

+   S20   =  (-10,-20)

+   W10  =  (-10,-10)

+   D30  =  (20,-10)

+   x    =  無效

+   A1A   =  無效

+   B10A11   =  無效

+  一個空 不影響

+   A10  =  (10,-10)

結果 (10, -10)

輸入描述:

一行字串

輸出描述:

最終座標,以,分隔

思路分析

本題給出了當方向為A、D、W、S時,運動的方向,只需要將X座標或Y座標進行加/減操作。在處理過程中,需要進行非法座標的識別,當座標值操作兩位時為非法,當座標中含有字母時為非法,當字串長度大於3時為非法。將這些非法情況分析清楚,本題的程式碼也就不難完成了。參考程式碼如下所示。

package HUAWEI;

import java.util.Scanner;

public class MovePosition {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
		while(scanner.hasNext()) {
			String input = scanner.next();
			String[] array = input.split(";");
			int beginX = 0;
			int beginY = 0;
			
			for(int i = 0; i < array.length; i++) {
				String current = array[i];
				// 數字位2為以內
				if(current.length() > 3 || current.length() == 0) {
					continue;
				}
				String gotoWhich = current.substring(0, 1);
				String distance = current.substring(1);

				try {
					Integer.parseInt(distance);
				} catch (Exception e) {
					continue;
				}
				
				if(gotoWhich.equals("A")) {
					beginX -= Integer.parseInt(distance);
				} else if(gotoWhich.equals("S")) {
					beginY -= Integer.parseInt(distance);
				} else if(gotoWhich.equals("W")) {
					beginY += Integer.parseInt(distance);
				} else if(gotoWhich.equals("D")) {
					beginX += Integer.parseInt(distance);
				}
			}
			
			System.out.println(beginX + "," + beginY);
		}
		scanner.close();
	}
}

2、識別有效的IP地址和掩碼並進行分類

題目描述

請解析IP地址和對應的掩碼,進行分類識別。要求按照A/B/C/D/E類地址歸類,不合法的地址和掩碼單獨歸類。

所有的IP地址劃分為 A,B,C,D,E五類

A類地址1.0.0.0~126.255.255.255;

B類地址128.0.0.0~191.255.255.255;

C類地址192.0.0.0~223.255.255.255;

D類地址224.0.0.0~239.255.255.255;

E類地址240.0.0.0~255.255.255.255

私網IP範圍是:

10.0.0.0~10.255.255.255

172.16.0.0~172.31.255.255

192.168.0.0~192.168.255.255

子網掩碼為前面是連續的1,然後全是0。(例如:255.255.255.32就是一個非法的掩碼)

本題暫時預設以0開頭的IP地址是合法的,比如0.1.1.2,是合法地址

輸入描述:

多行字串。每行一個IP地址和掩碼,用~隔開。

輸出描述:

統計A、B、C、D、E、錯誤IP地址或錯誤掩碼、私有IP的個數,之間以空格隔開。

思路分析:

本題是識別輸入的IP地址和掩碼是否符合要求,主要考慮不合法的情況,如:當不符合IPV4形式的IP均為不合法,某一區間值大於255不合法,子網掩碼第一個0之後還含有1也不合法。考慮清楚這些不合法的問題後,就根據題意進行判斷相應的A、B、C、D、E類IP地址的個數。

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class Main {
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        int typeA = 0;
        int typeB = 0;
        int typeC = 0;
        int typeD = 0;
        int typeE = 0;
        int errorIpOrMaskCode = 0;
        int privIp = 0;
         
        while (scanner.hasNext()) {
            String ipt = scanner.nextLine();
            String[] ipAndMaskCode = ipt.split("~");
            String ip = ipAndMaskCode[0];
            String maskCode = ipAndMaskCode[1];
            // 判斷格式
            if (!isValidFormat(ip) || !isValidFormat(maskCode)) {
                errorIpOrMaskCode++;
                continue;
            }
 
            // 判斷掩碼是否錯誤
            if (!validMaskCode(maskCode)) {
                errorIpOrMaskCode++;
                continue;
            }
 
            // 判斷ip類別
            String fnStr = ip.substring(0, ip.indexOf("."));
            int fn = Integer.valueOf(fnStr);
            if (fn >= 1 && fn < 127) {
                // A
                typeA++;
            } else if (fn >= 128 && fn < 192) {
                // B
                typeB++;
            } else if (fn >= 192 && fn < 224) {
                // C
                typeC++;
            } else if (fn >= 224 && fn < 240) {
                // D
                typeD++;
            } else if (fn >= 240 && fn <= 255) {
                // E
                typeE++;
            }
 
            // 判斷是否是私網IP
            String ipSubStr = ip.substring(ip.indexOf(".") + 1);
            String snStr = ipSubStr.substring(0, ipSubStr.indexOf("."));
            int sn = Integer.valueOf(snStr);
            if (fn == 10 || (fn == 172 && sn >= 16 && sn <= 31) || (fn == 192 && sn == 168)) {
                privIp++;
            }
//          System.out.printf("%d %d%n", fn, sn);
 
        }
        scanner.close();
 
        System.out.printf("%d %d %d %d %d %d %d%n", typeA, typeB, typeC, typeD, typeE, errorIpOrMaskCode, privIp);
 
    }
 
    /**
     * 判斷ip和掩碼是否是xxx.xxx.xxx.xxx格式Ø
     * @param ip
     * @return
     */
    private static boolean isValidFormat(String ip) {
        boolean res = true;
        if (ip == null || "".equals(ip))
            return false;
        Pattern pattern = Pattern.compile("^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$");
        Matcher matcher = pattern.matcher(ip);
         
        if (matcher.matches()) {
            String[] nums = ip.split("\\.");
            for (String num : nums) {
                int n = Integer.valueOf(num);
                if (n < 0 || n > 255) {
                    res = false;
                    break;
                }
            }
        } else {
            res = false;
        }
         
        return res;
    }
 
    /**
     * 判斷掩碼是否是前面全為1後面全為0 的格式
     *
     * @param maskCode
     * @return
     */
    private static boolean validMaskCode(String maskCode) {
        boolean res = true;
        String[] nums = maskCode.split("\\.");
        StringBuilder sb = new StringBuilder();
        for (String num : nums) {
            int n = Integer.valueOf(num);
            sb.append(binaryString(n));
        }
        int firstIndexOf0 = sb.indexOf("0");
        int lastIndexOf1 = sb.lastIndexOf("1");
        if (firstIndexOf0 < lastIndexOf1) {
            res = false;
        }
        return res;
    }
     
    /**
     * 將整數轉成對應的八位二進位制字串
     * @param num
     * @return
     */
    private static String binaryString(int num) {
        StringBuilder result = new StringBuilder();
        int flag = 1 << 7;
        for (int i = 0; i < 8; i++) {
            int val = (flag & num) == 0 ? 0 : 1;
            result.append(val);
            num <<= 1;
        }
        return result.toString();
    }
 
}

3、簡單密碼

題目描述

密碼是我們生活中非常重要的東東,我們的那麼一點不能說的祕密就全靠它了。哇哈哈. 接下來淵子要在密碼之上再加一套密碼,雖然簡單但也安全。

假設淵子原來一個BBS上的密碼為zvbo9441987,為了方便記憶,他通過一種演算法把這個密碼變換成YUANzhi1987,這個密碼是他的名字和出生年份,怎麼忘都忘不了,而且可以明目張膽地放在顯眼的地方而不被別人知道真正的密碼。

他是這麼變換的,大家都知道手機上的字母: 1--1, abc--2, def--3, ghi--4, jkl--5, mno--6, pqrs--7, tuv--8 wxyz--9, 0--0,就這麼簡單,淵子把密碼中出現的小寫字母都變成對應的數字,數字和其他的符號都不做變換,

宣告:密碼中沒有空格,而密碼中出現的大寫字母則變成小寫之後往後移一位,如:X,先變成小寫,再往後移一位,不就是y了嘛,簡單吧。記住,z往後移是a哦。

輸入描述:

輸入包括多個測試資料。輸入是一個明文,密碼長度不超過100個字元,輸入直到檔案結尾

輸出描述:

輸出淵子真正的密文

思路分析:

本題可以用Map儲存每一個小寫字母密文對應的明文,Map的查詢速度也是極快的。參考程式碼如下所示。

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {
	private static Map<Character, Integer> map;
	
	static {
		map = new HashMap<>();
		map.put('a', 2);
		map.put('b', 2);
		map.put('c', 2);
		map.put('d', 3);
		map.put('e', 3);
		map.put('f', 3);
		map.put('g', 4);
		map.put('h', 4);
		map.put('i', 4);
		map.put('j', 5);
		map.put('k', 5);
		map.put('l', 5);
		map.put('m', 6);
		map.put('n', 6);
		map.put('o', 6);
		map.put('p', 7);
		map.put('q', 7);
		map.put('r', 7);
		map.put('s', 7);
		map.put('t', 8);
		map.put('u', 8);
		map.put('v', 8);
		map.put('w', 9);
		map.put('x', 9);
		map.put('y', 9);
		map.put('z', 9);
	}
	
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
		while(scanner.hasNext()) {
			String input = scanner.next();
			changeInput(input);
		}
		
		scanner.close();
	}

	private static void changeInput(String input) {
		StringBuffer buffer = new StringBuffer();
		
		for(int i = 0; i < input.length(); i++) {
			char current = input.charAt(i);
			if(current >= 'A' && current <= 'Z') {
				current = Character.toLowerCase(current);
				current = (char) (current + 1);
				if(current > 'z') {
					current = 'a';
				}
				buffer.append(current);
			} else if(current >= 'a' && current <= 'z') {
				buffer.append(map.get(current));
			} else {
				buffer.append(current);
			}
		}
		
		System.out.println(buffer.toString());
	}
}

       每一週的華為筆試都在週三的晚上有條不紊的進行,機會總是留給有準備的人,它就在哪裡,只要實力足夠,它就是你的。我相信通過不斷的練習,自己的演算法能力是能有所提高的。加油了,大家。