leetcode—math.logic(3)

400. Nth Digit

class Solution {
    public int findNthDigit(int n) {
        int level = 1, start = 1; //标记第一层
        long count = 9; // count 代表每一层数字的总数量,一定是long类型,不然报错
        // 1(第一层) 1--9   9(9位数)       1(开始)
        // 2        10-99  (90*2=180位数) 10 开始
        while(n > level * count) {
            n -= level * count;
            level += 1;
            start *= 10;
            count *= 10;
        }
        start += (n - 1) / level;
        String s = Integer.toString(start);
        return s.charAt((n -1) % level) - '0';
    }
}

223. Rectangle Area

class Solution {
    public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
        // 找到overlap(如果有)的左下和右上2个坐标8个点
        int leftTopX = Math.max(ax1, bx1);
        int leftTopY = Math.min(ay2, by2);
        int leftBotX = leftTopX;
        int leftBotY = Math.max(ay1, by1);

        int rightTopX = Math.min(ax2, bx2);
        int rightTopY = leftTopY;
        int rightBotX = rightTopX;
        int rightBotY = leftBotY;

        // 2个长方形之和
        int total = Math.abs(ax2 - ax1) * Math.abs(ay2 - ay1) + Math.abs(bx2 - bx1) * Math.abs(by2 - by1);
        //判断2个长方形如果没有重叠
        if(ax2 <= bx1 || ax1 >= bx2 || ay1 >= by2 || by1 >= ay2) {
            return total;
        }
        // 不然就是有重叠 减去重叠部分
        return total - Math.abs(rightTopX - leftTopX) * Math.abs(rightTopY - rightBotY);
    }
}

172. Factorial Trailing Zeroes

class Solution {
    public int trailingZeroes(int n) {
        // 10 = 2 * 5 统计2 和 5 的个数,偶数都有2, 所以统计5的个数
        /*
        O(log_5(N)) (base 5!) is faster than any polynomial. 
        You need no more than 14 iterations to get the result. 
        You just need to count how many times 5 appears in n! 
        during multiplication in different forms: 5, 25, 125, 625, ... . 
        when any 5 is multiplied by 2 (we have many of them) then we get 0 at the end. 
        */
        int res = 0;
        while(n > 0) {
            n = n / 5;
            res += n;
        }
        return res;
    }
}

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值