您的位置:首页 > 编程语言 > Java开发

华为Java上机题 2012

2013-09-09 21:49 375 查看
public static void main(String[] args) {
// 1
// delete_sub_str("123afd123erwdf123rwer123", "123");

// 2
String[] arr = { "1", "2", "3", "3", "2", "1" };
// isHuiwen(arr);

// 3
float[] arr1 = { 1, 5, 3, 7, 8 };// ,4,8,2,9,10};
// aveScore(arr1, 5);

// 4
int[] arr2 = { 1, 5, 3, 7, 8, 4, 9, 2, 10, 11, 13, 15 };
odd_Even_Sort(arr2, 12);
}


1. 删除子串,只要是原串 str 中有相同的子串sub_str就删掉,不管有多少个,返回子串个数;

   输入:[原串] 123afd123erwdf123rwer123,[子串] 123

   输出:4 , [原串] afderwdfrwer

   方法接口:void delete_sub_str(String str,String substr);

public class TestThree {

public static void main(String[] args) {
delete_sub_str("123afd123erwdf123rwer123", "123");
}
public static void delete_sub_str(String str,String substr){
int count=0;
int sublen=substr.length();

for(int i=0;i<str.length()-sublen+1;i++){
if(str.substring(i, i+sublen).equals(substr)){
count++;
str=str.substring(0, i)+str.substring(i+sublen, str.length());
System.out.println(str);
}
}
System.out.println("Num: "+count);
}
}


2、比较一个数组的元素 是否为回文数组(回文数组就是无论从左到右还是从右到左读出来都一样的,例如:sdfds )

      方法接口:isHuiwen(String arr[])

   

public static void isHuiwen(String arr[]){
int len = arr.length;
boolean b=false;
for(int i=0;i<len/2;i++){
if(arr[i] != arr[len-i-1]){
b=true;
break;
}
}
if(b)
System.out.println("no");
else
System.out.println("yes");
}


另一种方法:

public static int huiwen(int num)
{
String ori = num+"";
StringBuffer buffer = new StringBuffer(ori);

if (buffer.reverse().toString().equals(ori))
return 1;

return 0;

}


3、算分数的问题,去掉一个最高分一个最低分,求平均分 aveScore(分数数组,数组长度);

    方法接口:aveScore(float score[], int n)

   

public static void aveScore(float score[], int n) {
float max = score[0];
float min = score[0];
float total = 0;
for (int i = 0; i < n; i++) {
if (score[i] > max)
max = score[i];
if (score[i] < min)
min = score[i];
total += score[i];
}
total = total - min - max;
System.out.println("最高分:" + max + ",   最低分:" + min);
System.out.println("平均分:" + total / (n - 2));
}


4、对一个数组,将数组中偶数从大到小排序,奇数从小到大排序, 奇数和偶数交叉着放且输出数组第一位放奇数,若奇数和偶数不等长,则把剩下的直接放到数组中。 

     方法接口:void odd_Even_Sort(int[] arr, int n)

     输入:int[] arr2 = { 1, 5, 3, 7, 8, 4, 9, 2, 10, 11, 13, 15 }; 

     输出:1  2  3  4  5  8  7  10  9  11  13  15  

public static void odd_Even_Sort(int[] arr, int n) {
int[] srrSorted = new int
;

List<Integer> odd = new ArrayList<Integer>();
List<Integer> even = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0)
even.add(arr[i]);
else
odd.add(arr[i]);
}
// 排序
Collections.sort(odd);
Collections.sort(even);

for (int i = 0, j = 0; i < n;) {
if (odd.size() > 0 && j < odd.size()) {
srrSorted[i++] = odd.get(j);
}
if (even.size() > 0 && j < even.size()) {
srrSorted[i++] = even.get(j);
}
j++;
}

for (int i = 0; i < n; i++) {
System.out.print(srrSorted[i] + "  ");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  华为 java上机