当前位置:网站首页>经典题目刷一刷
经典题目刷一刷
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
边栏推荐
猜你喜欢
ESP32程序下载失败,提示超时
Talk about the basic but not simple stock data
JVM工具之Arthas使用
[C语言] 文件操作《一》
一个必看的微信小程序开发指南1-基础知识了解
【深度好文】Flink SQL流批⼀体化技术详解(一)
'bully' Oracle enlarged its move again, and major enterprises deleted JDK overnight...
跨域配置报错: When allowCredentials is true, allowedOrigins cannot contain the special value “*“
ansible自動化運維詳解(一)ansible的安裝部署、參數使用、清單管理、配置文件參數及用戶級ansible操作環境構建
【路科V0】验证环境2——验证环境组件
随机推荐
信息收集相关知识点及题解
LINQ Learning Series ----- 1.4 anonymous objects
Transformer XL: attention language modelsbbeyond a fixed length context paper summary
[learning] audio and video development from scratch (9) -- nuplayer
QT reading and writing XML files
00后最关注的职业:公务员排第二,第一是?
Kubernetes如何使用harbor拉去私有镜像
【学习】从零开始的音视频开发(9)——NuPlayer
DOM learning - add + - button
SYS_CONNECT_BY_PATH(column,'char') 结合 start with ... connect by prior
洋桃电子STM32物联网入门30步笔记三、新建CubeIDE工程和设置讲解
如何保护开源项目免遭供应链攻击-安全设计(1)
洋桃电子STM32物联网入门30步笔记四、工程编译和下载
Anonymous type (c Guide Basics)
One click cleanup of pycharm and jupyter cache files under the project
什么是RPC
How to generate assembly file
Input / output system
Ear acupoint diagnosis and treatment essay 0421
Yangtao electronic STM32 Internet of things entry 30 step notes II. Cube ide download, installation, sinicization and setting