题目描述:通过键盘录入数组,一个整型数组里除了一个数字外,其他的数字都出现两次,找出这个数字。
键盘录入:[1,3,4,4,3,1,5]
键盘输出:5
详细代码:
public class shuzu {
public static void main(String[] args) {
//fun2();
fun1();
}
//方法二:通过TreeMap集合方法求出
public static void fun2(){
int[] a = tool();
TreeMap<Integer, Integer> hm = new TreeMap<Integer, Integer>();
for(Integer i : a){
if(hm.containsKey(i))
hm.put(i, hm.get(i)+1);
else
hm.put(i, 1);
}
for(Map.Entry<Integer, Integer> ar : hm.entrySet()){
if(ar.getValue()==1)
System.out.println(ar.getKey());
}
}
//方法一:通过异或的运算,找出一个数字
public static void fun1(){
int[] a = tool();
int result = a[0];
for(int j=1;j<a.length;j++){
result = a[j]^result;
}
System.out.println(result);
}
//把输入的数据存入到数组中
public static int[] tool() {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String line = str.substring(1, str.length()-1);
String[] buf = line.split(",");
int[] a = new int[buf.length];
for(int i=0;i<a.length;i++) {
a[i]=Integer.valueOf(buf[i]);
}
return a;
}
}
一. 通过键盘输入字符串([1,3,4,4,3,1,5]),首先要对输入的数据格式做处理,需用到String类的substring()方法,把输入的"[ ]"
去除,该方法参数为截取部分字符串,中有两个参数start和end,截取后包含头,不包含尾,所以start=1,end=str.length-1,
然后字符串变为"1,3,4,4,3,1,5", 再通过String类的split()方法, 按照","分割存到字符串数组中。再通过Integer类中的valueof()
方法即可将String类型数组转换为int类型数组。
二. 方法一:
通过位运算异或(^):
异或运算中,任何一个数字和自己本身异或都是0,任何一个数字和0异或都是本身。
通过该方法即可运用到该题中 ( 除了有两个数字只出现了一次,其他数字都出现了两次);所以从头到尾异或数组中
的每一 个数字,那些出现了两次的数字全部在异或中被抵消掉。
示例:(1,3,4,4,3,1,5)
1^3=2 2^4=6 6^4=2 2^3=1 1^1=0 0^5=5
异或的本质是通过位运算来计算 ,就是先把十进制的数先换为二进制,然后通过异或规则即可得到出现一次的数字。
三. 方法二:
利用集合Map
详细过程:通过遍历数组存到Map集合中在存入时进行判断,把数组中的元素存到Map集合中键里,依次判断存进的数
若集合中不存在,即存入,把值赋为一;若集合中存在,即把值加一,依次遍历完,当值为一的那个元素,即是数组中
只出现一次的数。