Displacement algorithm to determine whether element exists

Source: Internet
Author: User

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 ");
System. out. println (l );
String str = toStrFlag (l );
System. out. println (str );
System. out. println ("Whether the values of 11,12, 13,14 are in the range :"
+ ContainFlag (l, "11,12, 13,22, 23 "));
}


/**
* Convert the number list to the displacement number.
*/
Public static long toLongFlag (String flag) throws Exception {
Long result = 0;
If (StringUtils. isBlank (flag )){
Throw new Exception ("please pass the number List ");
}
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 ("This method supports a maximum of 31 bits, so please pass a number below 31 ");
}
Long l = 1 <(item-1 );
Result = result | l;
}
}
Return result;
}


/**
* Convert the displacement quantity to a number list.
*/
Public static String toStrFlag (long v ){
ArrayList List = new ArrayList ();
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 ,',');
}


/**
* Determines whether a number list exists in a specified displacement number.
*/
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;
}
}


}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.