快速幂
int qpow(int a, int b) {int ans = 1;while (b != 0) {if ((b & 1) != 0) {ans = ans * a;}a = a * a;b >>= 1;}return ans;}// 快速幂 + 递归class Solution {public:double quickMul(double x, long long N) {if (N == 0) {return 1.0;}double y = quickMul(x, N / 2);return N % 2 == 0 ? y * y : y * y * x;}double myPow(double x, int n) {long long N = n;return N >= 0 ? quickMul(x, N) : 1.0 / quickMul(x, -N);}};// 快速幂 + 迭代class Solution {public:double qpow(double x, long long n) {double ans = 1;while (n > 0) {if ((n & 1) == 1) {ans *= x;}x *= x;n >>= 1;}return ans;}double myPow(double x, int n) {long long N = n;return N >= 0 ? qpow(x, N) : 1.0 / qpow(x, -N);}};
400. 第 N 位数字
https://leetcode-cn.com/problems/nth-digit/
给你一个整数 n ,请你在无限的整数序列 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …] 中找出并返回第 n 位上的数字。
class Solution {public:int findNthDigit(int n) {if (n < 10) return n;// 计算前缀length// 1位数 9个 ===> 1 * 9// 2位数 90个 ===> 2 * 90// 3位数 900个 ===> 3 * 900long long length = 0, d = 1, count = 9;while (length+count*d < n) {length += count * d;d++;count *= 10;}// 在 pow(10, d-1) ~ pow(10, d) 之间,偏移量 (n-length-1) / d// 假如n是200,那么我们就知道它一定是三位数,且它是三位数里的第200-1*9-2*90=11位,// 转换成从0开始的坐标就是11−1=10,三位数是每三位一个数,那么它就是三位数里的10/3=3// 也就是在103这个数字里了。而我们要找该数里的10%3=1位也就是0。long long num = pow(10, d-1) + (n-length-1) / d;long long digitIndex = (n-length-1) % d;return to_string(num)[digitIndex] - '0';}};
233. 数字 1 的个数
class Solution {public:int countDigitOne(int n) {int high = n / 10;int curr = n % 10;int low = 0;long long digit = 1;int ans = 0;while (high != 0 || curr != 0) {if (curr == 0) {// 2304 [00|..|22]1_ans += high * digit;} else if (curr == 1) {// 2314 [00|..|22]1[0|..|4]ans += high * digit + low + 1;} else {// 2324 [00|..|22]1[0|..|9]ans += high * digit + digit;}low = curr * digit + low;curr = high % 10;high = high / 10;digit *= 10;}return ans;}};
