• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

wchenfeng

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

(2种)数字问题,计算1~2021中,有多少个数的数位中包含数字9?

方法一

函数提炼得不够好,所以代码看起来有点复杂。

不推荐使用本代码。

public class text2 {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		System.out.println("输出1~2021中,数位中包含数字9的数有:"+sum(2021));
	}
	public static int sum(int n)
	{
		int i,sum1=0,a=0,b=0;
		for (i=1; i<=n; i++) 
		{
			a=i;
			while(a>0)
			{
				b=a%10;
				if(b==9)
				{
					sum1++;
					break;
				}
				a/=10;
			}
		}
		return sum1;
	}
}

输出

 

 方法二

public class zimu9 {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		System.out.println(sum(2021));
	}
	public static int sum(int n)
	{
		int i,sum1=0,a=0,b=0;
		for (i=1; i<=n; i++) 
		{
				if(i%10==9||i/10%10==9||i/100%10==9)
					sum1++;

		}
		return sum1;
	}
}

 生活就像一大碗糖豆一样,谁也不知道下一颗究竟是什么。

posted on 2022-04-12 20:02  王陈锋  阅读(68)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3