华为机试准备--练习题(JAVA实现)

 第一题

    输入字符串长度len1,字符串s1,字符串长度len2,字符串s2。从后向前比较,以最短字符串为标准,输出不同的元素的个数。

    例如:  输入:s1="1,3,5"   len1=3        s2="2,4,1,7,5"   len2=5  

               输出:2(个人倒是觉得这个例子中输出应该为1,不知道是不是我题意理解错了。。。知道的同学请指正) 

    函数原型

public int getDiffNum(int len1, String s1, int len2, String s2) 

下面是代码:

public class Htest{
    public static void main(String[] args){
         String s1 = "1,3,5";
         String s2 = "2,4,1,7,5";
         int len1 = 3;
         int len2 = 5;
         Htest test = new Htest();
         int count = test.getDiffNum(len1, s1, len2, s2);
         System.out.println("不同元素个数为:"+count);
    }
    public int getDiffNum(int len1, String s1, int len2, String s2){
         int len = 0,result = 0;
         if(len1 > len2)
            len = len2;
         else
            len = len1;
         String[] a1 = s1.split(",");
         String[] a2 = s2.split(",");
         for(int i=0; i<len; i++)
            if(!a1[len1-i-1].equals(a2[len2-i-1]))
               result++;
         return result;
    }
}

第二题:输入字符串长度,字符串,计数m。从前往后计数,当数到m个元素时,m个元素出列(应该是第m个元素出列。。。。),同时将该元素赋值给m,然后从下一个数计数循环,直到所有数字都出列,给定的数全部为大于0的数字。输出出队队列。

    例如:  输入:len=4    str="3,1,2,4"   m=7   

             输出:2,3,1,4  

    函数原型

public String getOutString(int len, String str, int m) 

代码:

import java.util.List;
import java.util.ArrayList;

public class HuaWeiTest2{
      public static void main(String[] args){
           int len = 4, m = 7;
           String str = "3,1,2,4";
           HuaWeiTest2 test = new HuaWeiTest2();
           String outString = test.getOutString(len,  str, m);
           System.out.println("输出队列为:" + outString);
      }
      public String getOutString(int len, String str, int m){
           String result = "";
           String[] myStr = str.split(",");
           List<String> ls = new ArrayList<String>();
           for(int i=0; i<len; i++)
              ls.add(myStr[i]);
           for(int i=0; i<len; i++){
              int location = (m-1)%ls.size();
              result += ls.get(location);
              m = Integer.parseInt(ls.get(location))+location;
              ls.remove(location);
           }
           return result;
      }
}

此处需要注意

Java中List和ArrayList的区别

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值