Java:2的个数
发布日期:2021-05-11 02:22:12 浏览次数:12 分类:精选文章

本文共 1274 字,大约阅读时间需要 4 分钟。

2的个数

请编写一个方法,输出0到n(包括n)中数字2出现了几次。

给定一个正整数n,请返回0到n的数字中2出现了几次。

测试样例:

10
返回:1

在这里插入图片描述

注意:以上举例W为十位,当W当前位为个位,则最低位为0

public class Count2 {    public int countNumberOf2s(int n){        int count=0;//以122209为例,计算各位时2的个数        int low=0;//计算低位 此时低位为0        int current=0;//计算当前位9        int high=0;//计算高位 此时高位为12220        int flag=1;//标记此时是个位数1、十位数10还是百位数100    此时flag为1        while (n/flag !=0){            low=n-(n/flag)*flag;//12209-(12209/1)*1=0            current=(n/flag)%10;//(12209/1)%10=12209%10=9            high=(n/flag)/10;//(12209/1)/10=12209/10=1220            if(current==1 || current==0){//当前位 < 2的情况                count+=high*flag; //高位*flag            }else if(current==2){//当前位 = 2的情况                count+=high*flag+1+low;            }else { //当前位 > 2的情况                count+=(high+1)*flag;            }            flag*=10;        }        return count;    }}

这道题看了很久才想明白,也是自己太菜了,看了很多别人的答案才想过来,以下附上大神的答案,饮水思源

https://blog.csdn.net/ty6693/article/details/98077414?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522158622336919725219921134%2522%252C%2522scm%2522%253A%252220140713.130056874…%2522%257D&request_id=158622336919725219921134&biz_id=0&utm_source=distribute.pc_search_result.none-task-blog-all_SOOPENSEARCH-1

https://www.nowcoder.com/profile/4112248

上一篇:LeetCode236:二叉树最近的公共祖先
下一篇:LeetCode 155: 最小栈

发表评论

最新留言

感谢大佬
[***.8.128.20]2025年04月19日 02时21分24秒