题解 | #整数中1出现的次数#
整数中1出现的次数(从1到n整数中1出现的次数)
https://www.nowcoder.com/practice/bd7f978302044eee894445e244c7eee6
public class Solution { public int NumberOf1Between1AndN_Solution(int n) { int sum = 0; int level = 1; int high = n / 10; int low = 0; int cur = n % 10; while (high != 0 || cur != 0) { if (cur == 0) { sum = sum + high * level; } else if (cur == 1) { sum = sum + high * level + low + 1; } else { sum = sum + (high + 1) * level; } low = cur * level + low; level = level * 10; cur = high % 10; high = high / 10; } return sum; } }
解题思想:数学,推导公式:(高位+1)*当前位数=当前位数的次数
#算法##算法笔记#