首页 > 代码库 > 一道算法题

一道算法题

昨天看同事面试,里面有道题觉得挺有意思。如题:输入一个数如12, 检查里面1出现过几次(1,10,11,12)共出现5处1,其中11为两次。

 

        public staticint SumNumber(int n)

        {

            if (n < 0)

                return -1;

            if (n < 10)

                return n;

 

            int count = 0;

            while (n > 0)

            {

                int temp = n % 10;

                int temp1 = n / 10;

                if (temp == 1)

                   count += 1;

 

                while(temp1>0)

                {

                    int temp2 = temp1 % 10;

                    if (temp2 == 1)

                       count += 1;

                   temp1 = temp1 / 10;

                }

               

                n--;

            }

            return count;

 

        }

一道算法题