本文主要是介绍leetcode No233. Number of Digit One,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Question:
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
Algorithm:
Accepted Code:
class Solution {
public:int countDigitOne(int n) {if(n<=0)return 0;int higherDigit=0; //比当前位高一位的位,当前位轮了多少次0到9int curDigit=0; //当前位int lowerNums=0; //低位的大小long long total=0;long long factor=1;while(n/factor){higherDigit=n/(factor*10);curDigit=(n/factor)-(n/(factor*10))*10;lowerNums=n-(n/factor)*factor;switch(curDigit){case 0:total+=higherDigit*factor; break;case 1:total+=higherDigit*factor+lowerNums+1;break;default:total+=(higherDigit+1)*factor;}factor*=10;}return total;}
};
这篇关于leetcode No233. Number of Digit One的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!