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

LeetCode -- Count Digit One

时间:2015-09-20 00:30:17      阅读:126      评论: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.


本题目纯粹是找规律求解。


该实现参考了:


//Solution:
//For example ‘8192‘:
//
//1-999 -> countDigitOne(999)
//1000-1999 -> 1000 of 1s + countDigitOne(999)
//2000-2999 -> countDigitOne(999)
...
//7000-7999 -> countDigitOne(999)
//
//8000-8192 -> countDigitOne(192)
//
//Count of 1s : countDigitOne(999)*8 + 1000 + countDigitOne(192)
//
//Noticed that, if the target is ‘1192‘:
//
//Count of 1s : countDigitOne(999)*1 + (1192 - 1000 + 1) + countDigitOne(192)
//
//(1192 - 1000 + 1) is the 1s in thousands from 1000 to 1192.


链接:
https://leetcode.com/discuss/44496/5lins-solution-using-recursion




实现代码:




    public int CountDigitOne(int n) {
  
    if(n <= 0){
		return 0;
	}
    if(n < 10){
		return 1;
	}
	
	var result = 0;
    var digit = 1;
	var num = n;
    while (num > 0) {  
        var mod = num % 10;  
        var sign = mod > 0 ? 1 : 0;  
		
        num /= 10;
        int a = num * digit; 
        int b = sign * (mod == 1 ? n % digit + 1: digit);  
        result += a + b;  
        digit *= 10;  
    }  
    return result;  
    }


版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode -- Count Digit One

标签:

原文地址:http://blog.csdn.net/lan_liang/article/details/48575923

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