码迷,mamicode.com
首页 > 其他好文 > 详细

Number of Digit One

时间:2016-06-26 18:16:39      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

解题思路:计算任意一位上1的个数时,它会受三个因素的影响:该位上的数字,低位的数字以及高位的数字。

     如果该位的数字为0,则该位1的个数由高位决定,并且等于高位数字* 当前位数。

     如果该位的数字为1,则该位1的个数不仅由高位决定还由低位决定,并且等于高位数字* 当前位数 + 低位数字 + 1。

     如果该位的数字大于1,则该位1的个数由高位决定,并且等于(高位数字 + 1 )* 当前位数。

 1 public class Solution {
 2     public int countDigitOne(int n) {
 3         if (n <= 0) {
 4             return 0;
 5         }
 6         int num = n;
 7         int currNum = 0;
 8         int lowerNum = 0;
 9         int higerNum = 0;
10         int factor = 1;
11         int count = 0;
12         while (num != 0) {
13             lowerNum = n - num * factor;
14             higerNum = num / 10;
15             currNum = num % 10;
16             if (currNum == 0) {
17                 count += higerNum * factor;
18             } else if (currNum == 1) {
19                 count += higerNum * factor + lowerNum + 1;
20             } else {
21                 count += (higerNum + 1) * factor;
22             }
23             factor = factor * 10;
24             num = num / 10;
25         }
26         return count;
27     }
28 }

 

Number of Digit One

标签:

原文地址:http://www.cnblogs.com/FLAGyuri/p/5618186.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!