快速幂

  1. int qpow(int a, int b) {
  2. int ans = 1;
  3. while (b != 0) {
  4. if ((b & 1) != 0) {
  5. ans = ans * a;
  6. }
  7. a = a * a;
  8. b >>= 1;
  9. }
  10. return ans;
  11. }
  12. // 快速幂 + 递归
  13. class Solution {
  14. public:
  15. double quickMul(double x, long long N) {
  16. if (N == 0) {
  17. return 1.0;
  18. }
  19. double y = quickMul(x, N / 2);
  20. return N % 2 == 0 ? y * y : y * y * x;
  21. }
  22. double myPow(double x, int n) {
  23. long long N = n;
  24. return N >= 0 ? quickMul(x, N) : 1.0 / quickMul(x, -N);
  25. }
  26. };
  27. // 快速幂 + 迭代
  28. class Solution {
  29. public:
  30. double qpow(double x, long long n) {
  31. double ans = 1;
  32. while (n > 0) {
  33. if ((n & 1) == 1) {
  34. ans *= x;
  35. }
  36. x *= x;
  37. n >>= 1;
  38. }
  39. return ans;
  40. }
  41. double myPow(double x, int n) {
  42. long long N = n;
  43. return N >= 0 ? qpow(x, N) : 1.0 / qpow(x, -N);
  44. }
  45. };

400. 第 N 位数字

https://leetcode-cn.com/problems/nth-digit/
给你一个整数 n ,请你在无限的整数序列 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …] 中找出并返回第 n 位上的数字。

  1. class Solution {
  2. public:
  3. int findNthDigit(int n) {
  4. if (n < 10) return n;
  5. // 计算前缀length
  6. // 1位数 9个 ===> 1 * 9
  7. // 2位数 90个 ===> 2 * 90
  8. // 3位数 900个 ===> 3 * 900
  9. long long length = 0, d = 1, count = 9;
  10. while (length+count*d < n) {
  11. length += count * d;
  12. d++;
  13. count *= 10;
  14. }
  15. // 在 pow(10, d-1) ~ pow(10, d) 之间,偏移量 (n-length-1) / d
  16. // 假如n是200,那么我们就知道它一定是三位数,且它是三位数里的第200-1*9-2*90=11位,
  17. // 转换成从0开始的坐标就是11−1=10,三位数是每三位一个数,那么它就是三位数里的10/3=3
  18. // 也就是在103这个数字里了。而我们要找该数里的10%3=1位也就是0。
  19. long long num = pow(10, d-1) + (n-length-1) / d;
  20. long long digitIndex = (n-length-1) % d;
  21. return to_string(num)[digitIndex] - '0';
  22. }
  23. };

233. 数字 1 的个数

  1. class Solution {
  2. public:
  3. int countDigitOne(int n) {
  4. int high = n / 10;
  5. int curr = n % 10;
  6. int low = 0;
  7. long long digit = 1;
  8. int ans = 0;
  9. while (high != 0 || curr != 0) {
  10. if (curr == 0) {
  11. // 2304 [00|..|22]1_
  12. ans += high * digit;
  13. } else if (curr == 1) {
  14. // 2314 [00|..|22]1[0|..|4]
  15. ans += high * digit + low + 1;
  16. } else {
  17. // 2324 [00|..|22]1[0|..|9]
  18. ans += high * digit + digit;
  19. }
  20. low = curr * digit + low;
  21. curr = high % 10;
  22. high = high / 10;
  23. digit *= 10;
  24. }
  25. return ans;
  26. }
  27. };