移位算法判断是否存在元素

位移算法判断是否存在元素
package com.yanfan.test;


import java.util.ArrayList;
import org.apache.commons.lang.StringUtils;


public class Test_Binary {


public static void main(String[] args) throws Exception {
long l = toLongFlag("1,2,3,5,6,8,9,11,12,13,15,22");
System.out.println(l);
String str = toStrFlag(l);
System.out.println(str);
System.out.println("计算得到11,12,13,14是否在1,2,3,5,6,8,9,11,12,13,15,22中:"
+ containFlag(l, "11,12,13,22,23"));
}


/**
* 将数字列表转换成为位移数
*/
public static long toLongFlag(String flag) throws Exception {
long result = 0;
if (StringUtils.isBlank(flag)) {
throw new Exception("请传递数字列表");
}
String[] flags = flag.split(",");
for (String e : flags) {
if (StringUtils.isNotBlank(e)) {
e = e.trim();
int item = Integer.parseInt(e);
if (item > 31) {
throw new Exception("该方法最大支持31位,所以目前请传递31以下数字");
}
long l = 1 << (item - 1);
result = result | l;
}
}
return result;
}


/**
* 将位移数转换为数字列表
*/
public static String toStrFlag(long v) {
ArrayList<Integer> list = new ArrayList<Integer>();
char[] cs = Long.toBinaryString(v).toCharArray();
for (int i = cs.length - 1; i >= 0; i--) {
if (cs[i] == '1') {
list.add(cs.length - i);
}
}
return StringUtils.join(list, ',');
}


/**
* 判断某个数字列表是否存在于指定的位移数中
*/
public static boolean containFlag(long flags, String props) throws Exception {
long rep = toLongFlag(props);
rep = flags | rep;
if (rep == flags) {
return true;
} else {
return false;
}
}


}