0%

LeetCode

字符串分割

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
*输入一个字符串,请按长度为8拆分每个输入字符串并进行输出;
* 长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。
* 方案:补差达到8的倍数后分组打印
* @param args
*/
public static void main(String[] args) {

Scanner in = new Scanner(System.in);
String str = in.nextLine();
if (str.isEmpty()){
return;
}

StringBuilder wordBuilder = new StringBuilder();
wordBuilder.append(str);
int zeroCount = str.length() % 8 == 0 ? 0 : 8 - str.length() % 8;
for (int i = 1;i <= zeroCount;i++){
wordBuilder.append(0);
}
int groupLength = wordBuilder.length() / 8;
for (int i = 0;i < groupLength;i++){
System.out.println(wordBuilder.substring(i * 8,(i + 1) * 8));
}
}

进制转换

1
2
3
4
5
6
7
8
9
10
11
import java.util.*;

public class Main {
public static void main(String[] args) throws Exception{
Scanner in = new Scanner(System.in);
while(in.hasNextLine()){
String s = in.nextLine();
System.out.println(Integer.parseInt(s.substring(2,s.length()),16));
}
}
}

质数因子

、、

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()){
int num = in.nextInt();
int target = 2;
do {
if (num % target == 0){
System.out.print(target + " ");
num = num / target;
}else {
// 避免循环过多超时
if (target > num / target){
target = num;
}else {
target ++ ;
}
}
}while (num > 1);
}
}

取近似值

1
2
3
4
5
6
7
8
9
10
11
12
13
14

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextFloat()){
float num = in.nextFloat();
System.out.println(Math.round(num));

}
}
}

字符串排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

import java.util.*;
// Arrays.sort()排序
public class Main {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String[] array = new String[n];
for (int i = 0; i < n; i++) {
array[i] = in.nextLine();
}
Arrays.sort(array);
for (String str : array) {
System.out.println(str);
}
}
}

求 int 型正整数在内存中存储时 1 的个数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()){
String str = Integer.toString(in.nextInt(), 2);
char[] arrays = str.toCharArray();
int count = 0;
for (char array : arrays) {
if ("1".equals(String.valueOf(array))){
count ++ ;
}
}
System.out.println(count);
}
}
}

购物单【背包问题】