Java语言用什么语句可以简洁解决乌龟爬行问题,乌龟奇数天每天向前爬行3米,偶数天每天向后爬行距起点一半,多少天可以爬行n米,n从键盘输入,怎么实现呢
效果如图
代码如下
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入要爬行的距离(米):");
int distance = scanner.nextInt();
int days = 0; // 爬行的天数
int currentDistance = 0; // 当前已经爬行的距离
int step = 3; // 默认每次爬行的固定步长
while (currentDistance < distance) {
days++;
if (days % 2 == 0) { // 偶数天向后爬行距起点一半
step = currentDistance / 2;
} else { // 奇数天向前爬行3米
step = 3;
}
currentDistance += step;
}
System.out.println("乌龟爬行了 " + days + " 天,爬行距离为 " + currentDistance + " 米。");
}
}
问题:给定一个数组,数组中只有一个数仅出现过一次,其余数都出现过2次,请找出只出现1次的数
解题思路: 使用异或操作,利用其特性:a^a = a, a^0 = 0,且异或操作满足交换律和结合律!!!
public class Code3_singleNum {
public static void main(String[] args) {
int[] nums = new int[]{1, 4, 1, 2, 3, 3, 2};
System.out.println(singleNum(nums));
}
public static int singleNum(int[] nums) {
int res = 0;
for (int i = 0; i < nums.length; i++) {
// 相当于将数组的所有数,与0进行异或操作,然后通过交换律与结合律将2次出现的数异或为0,
// 最后只剩下0与出现1次的数异或,其结果就是该数本身
res ^= nums[i];
}
return res;
}
}
输出:4