软工一 Java homework practice 4

时间:2022-03-10 00:32:45

P1:判断丑数(只包含质因子 2, 3, 5 的正整数)

用函数代替减少代码量

P2:Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 

P3:输入一个整型数组,返回这个数组表示的数(上溢返回int最大值)

Integer.MAX_VALUE 

2147483647

Integer.MIN_VALUE

-2147483648

-----------------------------------

拆分pow10

P4:二分法,在一个数组中查找目标元素的下标

中间值+波动范围:

终止条件为---波动条件->0

public static int search(int[] data, int target) {
   if(data.length==0){
      return -1;
   }
   if (data[0]==target)
      return 0;
   int len = data.length;
   int p = len/2;
   len = p;
   for (;len!=1;){
      if (data[p]==target){
         return p;
      }
      else if (data[p]>target){
         p /= 2;
         len /= 2;
      }
      else if (data[p]<target){
         p = p + len/2;
         len /= 2;
      }
      else
         return -1;

   }
   if (data[p+len]==target){
      return p+len;
   }
   return -1;
}

头值+尾值:

终止条件为---start+1<end

public static int search(int[] data, int target) {
   int index;
   int start = 0;
   int end = data.length-1;
   while(start+1<end) {
      index = (start+end) / 2;
      if(data[index]==target) {
         return index;
      }
      else if(data[index]>target) {
         end = index-1;
      }
      else if(data[index]<target){
         start = index+1;
      }
   }
   return -1;
}
P5:判断是否为奇数