当前位置:网站首页>经典题目刷一刷
经典题目刷一刷
2022-04-23 08:17:00 【红苹果超好吃】
目录
1.查找输入整数中二进制1的个数
①题目及示例:
②方法解析:
这道题很像我们昨天刷过的一道题,它的目的是计算出二进制下1的个数,那么我们就可以利用按位与1来计算,将待计算数每次右移一位即可,结果是1,则count++;
但是这里还有值得注意的一点就是题目中强调了注意多组的输入输出,因此我们这里会用到scanner中的scanner.hasNext()这个方法,下面给大家看一看它的一些说明
这是查阅jdk1.8的结果。也就是说,在一组数据输出结束的时候,它并不会马上停止程序进程的运行,它会先让程序进行阻塞,以便输入下一组数据。
③代码如下:
import java.util.*; public class demo4 { public static void main(String[]args){ Scanner sc=new Scanner(System.in); while(sc.hasNext()){ int n=sc.nextInt(); int count=0; while(n!=0){ if((n&1)==1){ count++; } n>>=1; } System.out.println(count); } } }
2.完全数计算
①题目及示例:
②方法解析:
本题题意就不做过多讲解了,这个题很简单,主要就是要对约数和(除去本身)来进行判断。而这个题我们值得注意的是判断约数的时候范围截中选取就可以了,因为本来两者就是对应的。还有就是因为本身是不被选取的,所以我们可以把本身相对的约数1直接加在最后来进行判断。
③代码如下:
import java.util.*; public class Main { public static void main(String[]args){ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int count=0; for(int i=2;i<=n;i++){ if(isPerfectNum(i)){ count++; } }System.out.println(count); }//判断约数 public static boolean isPerfectNum(int i){ int sum=0; for(int j=2;j<Math.sqrt(i);j++){ if((i%j==0)){ sum+=j+(i/j); } } if(i==sum+1){ return true; }else{ return false; } } }
版权声明
本文为[红苹果超好吃]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_58850105/article/details/124350124
边栏推荐
猜你喜欢

分布式消息中间件框架选型-数字化架构设计(7)

My heart's broken! A woman's circle of friends envied others for paying wages on time and was fired. Even her colleagues who liked her were fired together

信息收集相关知识点及题解

HAL库的RCC简介

396. Rotate Function

SYS_CONNECT_BY_PATH(column,'char') 结合 start with ... connect by prior

Input / output system

项目上传部分

idea配置连接远程数据库MySQL,或者是Navicat连接远程数据库失败问题(已解决)

CGM optimizes blood glucose monitoring and management -- Yiyu technology appears in Sichuan International Medical Exchange Promotion Association
随机推荐
Queue (C language / linked list)
Failed to convert a NumPy array to a Tensor(Unsupported Object type int)
LINQ Learning Series ----- 1.4 anonymous objects
Goland 调试go使用-大白记录
[C语言] 文件操作《一》
【路科V0】验证环境2——验证环境组件
分组背包呀
Add listening event to input element
获取TrustedInstaller权限
测试你的机器学习流水线
什么是RPC
Detailed description of self feeling of auricular point weight loss 0422
The annotation is self-defined by implementing the parameter parser handlermethodargumentresolver interface
Detailed explanation of ansible automatic operation and maintenance (I) installation and deployment, parameter use, list management, configuration file parameters and user level ansible operating envi
AQS & ReentrantLock 实现原理
word加水印
Idea: export Yapi interface using easyyapi plug-in
00后最关注的职业:公务员排第二,第一是?
How to generate assembly file
Overview of bus structure
https://www.nowcoder.com/practice/1b46eb4cf3fa49b9965ac3c2c1caf5ad?tpId=37&&tqId=21285&rp=1&ru=/activity/oj&qru=/ta/huawei/question-ranking

