博客记录-day172-力扣

65 阅读2分钟

一、力扣

1、第 N 位数字

400. 第 N 位数字

image.png

class Solution {
    public int findNthDigit(int n) {
        // 初始化变量:当前数字位数,当前位数范围的起始数字,当前位数范围的总位数
        int digit = 1;
        long start = 1;
        long count = 9;
        
        // 确定n所在的数字位数范围
        while (n > count) {
            // 减去当前位数范围的所有位数,继续处理更高位数的部分
            n -= count;
            digit += 1;          // 进入下一个更高位数(如从1位到2位)
            start *= 10;         // 更新当前位数范围的起始数字(如1→10→100)
            // 计算新位数范围的总位数:位数 × 数字数量(如2位数有90个数字,总位数=2×90=180)
            count = digit * start * 9;
        }
        
        // 计算目标数字:start是当前位数范围的第一个数,(n-1)/digit确定是范围内的第几个数
        long num = start + (n - 1) / digit;
        
        // 将数字转为字符串,便于定位具体字符
        String ans = Long.toString(num);
        
        // 计算目标字符在字符串中的位置,并转换为整数返回
        // (n-1)%digit得到字符在数字中的索引,例如n=5,digit=2 → 索引0(第一个字符)
        return ans.charAt((n - 1) % digit) - '0';
    }
}

2、36进制加法

36进制加法_牛客题霸_牛客网

image.png

import java.util.*;


public class Solution {

    public String thirtysixAdd (String A, String B) {
        // write code here
        int pre = 0;
        StringBuilder ans = new StringBuilder();
        int x = A.length() - 1, y = B.length() - 1;
        while (x >= 0 || y >= 0 || pre > 0) {
            int fir = 0;
            if (x >= 0) {
                char temp1 = A.charAt(x);
                if (Character.isDigit(temp1)) {
                    fir = temp1 - '0';
                } else {
                    fir = temp1 - 'a' + 10;
                }
                x--;
            }
            int sec = 0;
            if (y >= 0) {
                char temp1 = B.charAt(y);
                if (Character.isDigit(temp1)) {
                    sec = temp1 - '0';
                } else {
                    sec = temp1 - 'a' + 10;
                }
                y--;
            }
            pre = pre + fir + sec;
            int target = pre % 36;
            pre = pre / 36;
            if (target < 10) {
                ans.append(target + "");
            } else {
                char temp = (char)(target - 10 + 'a');
                ans.append(temp);
            }
        }

        return ans.reverse().toString();
    }
}

3、加油站

134. 加油站

image.png

class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int n = gas.length;
        int curSum = 0;
        int totalSum = 0;
        int res = 0;
        for (int i = 0; i < n; i++) {
            curSum += gas[i] - cost[i];
            totalSum += gas[i] - cost[i];
            if (curSum < 0) {
                curSum = 0;
                res = (i + 1) % n;
            }
        }
        return totalSum >= 0 ? res : -1;
    }
}