int类型正整数在内存中存储为1的个数
import java.util.Scanner;
public class Main{
public static void main(String[] args){ //方法1
Scanner in = new Scanner(System.in);
int num = in.nextInt(); //读取数字
int n = 0; //计数变量
for(int i=0; i < 32; i++){
if((num&1) == 1) //如果末位为1则计数
n++;
num = num >>> 1; //无符号右移
}
System.out.println(n);
}
public static void main1(String[] args) { //求int型正整数在内存中存储时1的个数
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
String s=Integer.toBinaryString(num); //int类型数值转换成2进制的字符穿
String n=s.replace("0","");//字符串替换
System.out.print(n.length());
}
}
合并表记录
public static void main8(String[] args) { //合并表记录
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
Map<Integer,Integer>map=new TreeMap<>(); //不要用HashMap 会有部分用例过不去
while(sc.hasNext()) {
int key = sc.nextInt();
int val = sc.nextInt();
if(!map.containsKey(key)) {
map.put(key,val);
} else {
//map.get(key);
map.put(key,map.get(key)+val);
}
}
//循环遍历打印
Iterator<Integer> iterator=map.keySet().iterator();
while (iterator.hasNext()) {
Integer key=iterator.next();
Integer val=map.get(key);
System.out.println(key+" "+val);
}
}
质数因子
输入一个正整数,按照从小到大顺序打印所有质数因子如180:2 2 3 3 5
public static void main6(String[] args) { //质数因子 质数是只有1和本身可以整除它
Scanner sc=new Scanner(System.in);
long l=sc.nextLong();
long num=(long) Math.sqrt(l);
for (long i=2;i<=num;i++) { //注意Long不行只能是long
while (l%i==0) {
System.out.print(i+" ");
l=l/i;
}
}
System.out.print(l==1 ? "":l+" ");
}
进制转换
4、任意进制的数字转换成10进制 Long.parseLong(“带转换的数字”, 你的数字是几进制的) 可以16进制 2 进制 等
-
Integer.toHexString(sc.nextInt());10进制转成16进制
- 十六进制字符串转换为十进制数字(Integer.valueOf 或 Integer.parseInt均可指定radix)
Long.parseLong(sc, X) ===X进制数转10进制注意这里sc是String类型 返回值是void类型 Integer.toString(num,Y) 十进制的num转成Y进制数据 这里num类型为int
public static void main5(String[] args) { // 16进制数字转换成10进制
Scanner sc=new Scanner(System.in);
while(sc.hasNext()) {
//下面这两行代码是为了把16进制的数最开始会有0x的标识 将他俩去掉
String s=sc.nextLine();
s=s.substring(2);
System.out.println(Long.parseLong(s, 16));
}
}
字符串分割
字符串等于8就直接打印,大于8打印前八个后面不够8 的补0打印
public static void main4(String[] args) { //字符串分隔
Scanner sc=new Scanner(System.in);
while(sc.hasNext()) {
String s=sc.nextLine();
if(s.length()==8) {
System.out.println(s);
}else{
while(s.length()>8) {
System.out.println(s.substring(0,8));
s=s.substring(8);
}
while(s.length()<8) {
s=s+"0";
}
System.out.println(s);
}
}
}
明明的随机数 给数组对数组去重+排序
Treeset
public static void main3(String[] args) { //明明的随机数 不要一下子想的太复杂 要想做一个简单的
Scanner s=new Scanner(System.in);
while(s.hasNext()) {
//获取这组数据长度
int a=s.nextInt();
//去重+排序
TreeSet set=new TreeSet();
int b=a;
while(b>0) {
set.add(s.nextInt());
b--;
}
//打印输出
Iterator in=set.iterator();
while (in.hasNext()) {
System.out.println(in.next());
}
}
}
忽略大小写计算b输入的字符在a中出现的次数
public static void main2(String[] args) { //
Scanner s=new Scanner(System.in);
String a=s.nextLine();
String b=s.nextLine();
char[] c=a.toCharArray();
int num=0;
for(int i=0;i<c.length;i++) {
if(String.valueOf(c[i]).equalsIgnoreCase(b)){ //就这一行
num++;
}
}
System.out.println(num);
}