给你一个整数 n ,请你在无限的整数序列 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...] 中找出并返回第 n 位上的数字。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/nth-digit
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.Scanner; class Solution { public int findNthDigit(int n) { int digitCnt = 1; int base = 1; while (1L * digitCnt * base * 9 < n) { n -= digitCnt * base * 9; digitCnt++; base *= 10; } int num = base + (n % digitCnt == 0 ? (n / digitCnt) : (n / digitCnt + 1)) - 1; return String.valueOf(num).charAt(n % digitCnt == 0 ? digitCnt - 1 : n % digitCnt - 1) - '0'; } public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { System.out.println(new Solution().findNthDigit(in.nextInt())); } } }