1丶丑数

【Java】一只小菜坤的编程题之旅【2】-LMLPHP

因为丑数只能被2,3,5整除,所以让n依次去除2,3,5,如果最后是n为1,就说明是丑数。

class Solution {
    public boolean isUgly(int n) {
        if(n <= 0){
            return false;
        }
        while(n % 2 == 0){
            n /= 2;
        }
        while(n % 3 == 0){
            n /= 3;
        }
        while(n % 5 == 0){
            n /= 5;
        }
        return n == 1;
    }
}

2、各位相加

【Java】一只小菜坤的编程题之旅【2】-LMLPHP

class Solution {
    public int addDigits(int num) {
        if(num<10)
        return num;
        while(num>=10){
             int sum=0;
            while (num > 0) {
                sum += num % 10;
                num /= 10;
            }
            num=sum;
        }
    return num;

    }
}

3丶搜索插入位置

【Java】一只小菜坤的编程题之旅【2】-LMLPHP
本小菜坤的答案:

class Solution {
    public int searchInsert(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target) {
                return i;
            }
        }
            int place=0;
            for (int j = 0;  j< nums.length-1; j++) {
                if (nums[j] <= target && nums[j + 1] >= target) {
                return j+1;
                }
            }
            if(nums[nums.length-1]<target){    //判断最后一个元素
                return nums.length;
            }
            return 0;
            
    }

}

4丶第一个错误的版本

【Java】一只小菜坤的编程题之旅【2】-LMLPHP
【Java】一只小菜坤的编程题之旅【2】-LMLPHP
看着题目挺复杂,其实思想就是二分查找的思想。

/* The isBadVersion API is defined in the parent class VersionControl.
      boolean isBadVersion(int version); */

public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        int left=1;
        int right=n;
        while(left<right){
            int mid=left+(right-left)/2;  //中间值没有设置为(left+right)/2的原因是,当left和right都是非常大的整数时防止运算溢出
            if(isBadVersion(mid)){
                right=mid;
            }
            else{
                left=mid+1;
            }
        }
        return left;

        
    }
}
07-12 18:26