面试遇到了 <计算从1到N中1的出现次数>结果悲剧了.

面试遇到<计算从1到N中1的出现次数>这个题,结果没能做出来.下面是这道题的三种解法.简要的记录一下.

View Code
namespace n中1出现的次数
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(CountOne2(911111111099999009));
        }
        //最简单,容易理解的解法
        public static long CountOne3(long n)
        {
            long i = 0, j = 1;
            long count = 0;
            for (i = 0; i <= n; i++)
            {
                j = i;
                while (j != 0)
                {
                    if (j % 10 == 1)
                        count++;
                    j = j / 10;
                }
            }
            return count;
        }
        //效率最好的解法
        public static long CountOne2(long n)
        {
            long count = 0;
            long i = 1;
            long current = 0, after = 0, before = 0;
            while ((n / i) != 0)
            {
                current = (n / i) % 10;
                before = n / (i * 10);
                after = n - (n / i) * i;

                if (current > 1)
                    count = count + (before + 1) * i;
                else if (current == 0)
                    count = count + before * i;
                else if (current == 1)
                    count = count + before * i + after + 1;

                i = i * 10;
            }
            return count;
        }

        //递归解法,效率一般
        public static long CountOne(long n)
        {
            long count = 0;
            if (n == 0)
                count = 0;
            else if (n > 1 && n < 10)
                count = 1;
            else
            {
                long highest = n;//表示最高位的数字
                int bit = 0;
                while (highest >= 10)
                {
                    highest = highest / 10;
                    bit++;
                }

                int weight = (int)Math.Pow(10, bit);//代表最高位的权重,即最高位一个1代表的大小
                if (highest == 1)
                {
                    count = CountOne(weight - 1)
                    + CountOne(n - weight)
                    + n - weight + 1;
                }
                else
                {
                    count = highest * CountOne(weight - 1)
                    + CountOne(n - highest * weight)
                    + weight;
                }
            }
            return count;
        }

    }
}

原文详细解说地址:http://www.nowamagic.net/algorithm/algorithm_CountOccurrencesOfOne.php

posted @ 2012-08-01 20:04  ``炯``  阅读(312)  评论(2编辑  收藏  举报