1.序列找数
题目描述:从非负整数序列0,1,2,….,n中给出包含其中n个数的子序列,请找出未出现在该子序列中的那个数。
输入描述:输入为n+1个非负整数,用空格分开。
其中:首个数字为非负整数序列的最大值n,后面n个数字为子序列中包含的数字。
输出描述:输出为1个数字,即未出现在子序列中的那个数。
示例:
输入:
3 3 0 1
输出:
2
package org.buptdavid.datastructure.array;
import java.util.Scanner;
/**
* 序列找数
* Created by ZD on 2018/4/10.
*/
public class Main_Z1 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if (n >= 0){
StringBuilder b = new StringBuilder();
for (int i = 0; i < n; i++){
b.append(sc.nextInt());
}
findNoNumber(b.toString());
}
}
/**
* 找到未出现在该子序列中的数
* @param s
*/
private static void findNoNumber(String s) {
if (s == null || s.length() == 0)
return;
for (int i = 0; i <= s.length(); i++){
if (!s.contains(" "+i+" ")){
System.out.println(i);
return;
}
}
}
}
2.小招喵跑步
题目描述:
小招喵喜欢在数轴上跑来跑去,假设它现在站在点n处,它只会3种走法,分别是:
1.数轴上向前走一步,即n=n+1;
2.数轴上向后走一步,即n=n-1;
3.数轴上使劲跳跃到当前点的两倍,即n=2*n
现在小招喵在原点,即n=0,它想去点x处,快帮小招喵算算最快的走法需要多少步?
输入描述:
小招喵想去的位置x
输出描述:
小招喵最少需要的步数
示例:
输入:
3
输出:
3
import java.util.Scanner;
/**
* 小招猫跑步
* Created by ZD on 2018/4/10.
*/
public class Main_Z2 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
long x = sc.nextLong();//目的地
System.out.println(countQuickSteps(x));
}
}
/**
* 计算最快走法需要多少步
* @param x
*/
private static long countQuickSteps(long x) {
if (x < 0)
x = -x;
long quickSteps;
if (x == 0)
return 0;
if (x == 1)
return 1;
if (x == 2)
return 2;
if (x % 2 == 0){
quickSteps = countQuickSteps(x/2) + 1;
}else {
quickSteps = countQuickSteps(x / 2) + 2;
}
return quickSteps;
}
}
3.满足条件的数字
题目描述:
如果一个正整数,它的质因数只包含2,3,5,那么这个数满足条件。
同时,特别规定1也是满足条件的数字。
示例:前10个满足条件的数字是1,2,3,4,5,6,8,9,10,12
请编写一个函数,返回第n个满足条件的数
输入描述:
输入为n
输出描述:
输出为第n个满足条件的数
示例:
输入:
5
输出:
5
package org.buptdavid.datastructure.array;
import java.util.Scanner;
/**
* Created by ZD on 2018/4/10.
*/
public class Main_Z3 {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt();
countN(n);
}
}
/**
* 打印出第n个满足条件的数
* @param n
*/
private static void countN(int n) {
if (n <= 0)
return;
int count = 1;
int number = 1;
while (count < n){
number++;
int temp = number;
boolean flag1 = true;
while (temp != 1 && flag1) {
if (temp % 2 == 0) {
temp = temp / 2;
flag1 = true;
continue;
}else {
flag1 = false;
}
if (temp % 3 == 0) {
temp = temp / 3;
flag1 = true;
continue;
}else {
flag1 = false;
}
if (temp % 5 == 0) {
temp = temp / 5;
flag1 = true;
continue;
}else {
flag1 = false;
}
}
if (temp == 1)
count++;
}
System.out.println(number);
}
}
说明:第二题只能通过80%,第三题,当n足够大时,时间复杂度高,所以只通过83%。