汽水瓶
我的代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n;
int sum;
while (in.hasNext()) {
sum = 0;
n = in.nextInt();
if (n == 0) {
return;
}
while (n >= 3) {
sum += (n / 3);
n = (n / 3) + (n - (n / 3) * 3);
}
if (n == 2) {
sum++;
}
System.out.println(sum);
}
}
}
其它思路:通过分析,每两个瓶子就可以换一瓶汽水,其中向老板借一个,凑成三个瓶子,能兑换一瓶,喝完以后,变成空瓶子还给老板
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n;
while (in.hasNextInt()) {
n = in.nextInt();
if (n == 0) {
return;
}
System.out.println(n / 2);
}
}
}
明明的随机数
我的代码:使用TreeSet
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int num;
Set<Integer> set = new TreeSet<>();
while (N > 0) {
N--;
num = in.nextInt();
set.add(num);
}
for (int i : set) {
System.out.println(i);
}
}
}
其它思路:根据题目所给的取值范围,开辟一个数组
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int num;
int[] arr = new int[1001];
while (N > 0) {
N--;
num = in.nextInt();
arr[num]++;
}
for (int i = 1; i < arr.length; i++) {
if (arr[i] > 0) {
System.out.println(i);
}
}
}
}
进制转换
我的代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
int num = 0;
for (int i = 2; i < str.length(); i++) {
char c = str.charAt(i);
switch (c) {
case 'A':
case 'a':
num = num * 16 + 10;
break;
case 'B':
case 'b':
num = num * 16 + 11;
break;
case 'C':
case 'c':
num = num * 16 + 12;
break;
case 'D':
case 'd':
num = num * 16 + 13;
break;
case 'E':
case 'e':
num = num * 16 + 14;
break;
case 'F':
case 'f':
num = num * 16 + 15;
break;
default:
num = num * 16 + (c - '0');
break;
}
}
System.out.println(num);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
int num = 0;
for (int i = 2; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= 'A' && c <= 'F') {
num = num * 16 + c - 'A' + 10;
} else if (c >= 'a' && c <= 'f') {
num = num * 16 + c - 'a' + 10;
} else {
num = num * 16 + c - '0';
}
}
System.out.println(num);
}
}
其它思路:
Integer.parseInt(s, radix)可以转化,其中s为输入字符串,radix为进制数,返回值为int型十进制整数。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
System.out.println(Integer.parseInt(str.substring(2),16));
}
}