華為java機試面試題目大全

來源:互聯網
上載者:User

題目:
有n 個人圍城一圈每次從1數起數到3就把那個人提出圈子,最後只保留一個人。
輸入: 輸入人數字串
輸出:把最後一個人所保留位置返回出來。
比如你輸入11 的話即有11個人 [1,2,3,4,5,6,7,8,9,10,11] 。返回的是7.
如果輸入”123a” 的話,返回的是”0″。

 代碼如下 複製代碼

package com.javaer.huawei;
 
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
 
public class TestJosephRing {
 
public static void main(String args[]){
String n = "11";
TestJosephRing tj = new TestJosephRing();
System.out.println(tj.getTheLeftPerson(n));
}
 
public int getTheLeftPerson(String num){
 
Pattern p = Pattern.compile("[a-zA-Z]|p{Punct}");//處理非法字元
Matcher m = p.matcher(num);
if(m.find()){
return 0;
}
 
int n = Integer.parseInt(num);
List<Integer> pL = new ArrayList<Integer>();
for(int i=0; i<n; i++){
pL.add(i+1);
}
 
int count = 3;
for(int i=0; i<n-1; i++){
int temp = (count-1)%pL.size();//要移除的位置
pL.remove(temp);
count = temp+3; //保留被移除的位置,再加上計數
}
 
//最後肯定只剩下一個
return pL.get(0);
}
}

題目:

手動輸入一個字串,僅限小寫字母,統計並輸出每個字元在字串中出現的次數,並輸出。提示可以用map

例子:輸入:aaabbbccc

輸出:a 3

b 3

c 3

分析: 看到後面的提示,簡直就是不用動腦,直接簡單粗暴的順勢而上

直接上代碼:

 代碼如下 複製代碼

package com.javaer.huawei;
 
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
 
public class TestCharAcount {
 
public static void main(String args[]) {
String strIn = "aaabbbccc";
TestCharAcount tc = new TestCharAcount();
Map<Character, Integer> mTemp = tc.charAcount(strIn);
 
Set<Character> ks = mTemp.keySet();// 產生索引set
for (Iterator<Character> it = ks.iterator(); it.hasNext();) {// 遍曆索引取值
char c = it.next();
System.out.println(c + " " + mTemp.get(c));
}
 
}
 
public Map<Character, Integer> charAcount(String strIn) {
String tempStr = strIn;
 
// The map is sorted according to the natural ordering of its keys
// treemap是以鍵的自然順序來儲存值的
Map<Character, Integer> m = new TreeMap<Character, Integer>();
char[] strC = tempStr.toCharArray();
for (int i = 0; i < strC.length; i++) {
Integer count = m.get(strC[i]);
if (null == count)
count = 0;
 
count++;
m.put(strC[i], count);
}
 
return m;
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.