一道算法题

来源:互联网 发布:淘宝乐豆有什么用 编辑:程序博客网 时间:2024/05/29 04:44

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

 

        public staticint SumNumber(int n)

        {

            if (n < 0)

                return -1; 

            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;

 

        }

1 0
原创粉丝点击