- >>与<<
a << b, 表示a左移b位,等于a*(2^b);
a >> b , 表示a右移b位,等于a/(2^b)
- Scanner输入
输入字符串
public static void main(String[] args){
Scanner s =new Scanner(System.in);
while(s.hasNext()){
String str=s.next();
System.out.println(str);
}
}
输入:
My Name Is Wing
输出:
My
Name
Is
Wing
输入整数
public static void main(String[] args){
Scanner s =new Scanner(System.in);
while(s.hasNext()){
int str=s.nextInt();
System.out.println(str);
}
}
输入:
5 6 7
输出:
5
6
7
获取整行
public static void main(String[] args){
Scanner s =new Scanner(System.in);
while(s.hasNext()){
String str=s.nextLine();
System.out.println(str);
}
}
输入:
My Name Is Wing
输出:
My Name Is Wing
输入多行整数,当输入exit时,退出
public static void main(String[] args){
Scanner s =new Scanner(System.in);
while(true){
String str=s.next();
if(str.equals("exit")){
break;
}
int t=0;
try{
t=Integer.valueOf(str);
}
catch(NumberFormatException e){
System.out.println("输入格式有错误");
break;
}
System.out.println(t);
}
}
异或
问题:给出2n+1个数,其中有2n个数出现过两次,如何用最简便的方法找出里面只出现了一次的那个数。
public class Test {
public static void main(String[] args) {
int[] arr={3,3,1,1,2,4,2,5,10,5,4};
int res=0;//初始值
for(int i=0;i<arr.length;i++){
res ^=arr[i];
System.out.println(res);
}
System.out.println(res);
}
}
输出:
10
算法的原理就是:任何数与自己异或值都为0,任何数异或0值不变。
因此一个数两次异或同一个数,值不变。