The mathematical application of java development experience -java

The mathematical application of java development experience -java

Stored in digital form in the computer

reference:

https://blog.csdn.net/alpinistwang/article/details/87994617

1个字节是8位
只有8种基本类型可以算.其他引用类型都是由java虚拟机决定的自己不能操作
byte 1字节
short 2字节
int 4字节
long 8字节
float 4字节
double 8字节
char 2字节
boolean 1字节

Binary code of 1111 F
binary code of 0111 7
As a result, the entire binary integer representation is in addition to the first 0x7FFFFFFF is 0, 1 rest are

 

int binary digits: 32

short binary digits: 16

long binary digits: 64

float binary digits: 32

double binary digits: 64

 

int-type data in a computer to store a binary one int type 4 bytes, a byte of 8 bits, a total of 32 bits.
(1) The first one is the flag, the flag bit is 0 for positive, flag 1 indicates negative.
(2) the remaining 31 bits are used to represent the digital part

As principle, to store digital computer, the first is the flag, only 31-bit value to store numbers. So the largest positive number represented by 0,111,111,111,111,111 1,111,111,111,111,111, namely: 2 ^ 31-1 

 

int turn binary number

	public static void main(String[] args) {
		int a = 7;
		String binaryString = Integer.toBinaryString(a);
		System.out.println(binaryString);
	}

Output:

111

 

Computer Memory

Primitive
type int binary data in a computer memory, a data type int 4 bytes, a byte of 8 bits, a total of 32 bits.
(1) The first one is the flag, the flag bit is 0 for positive, flag 1 indicates negative.
(2) the remaining 31 bits are used to represent the digital part

Complement
in the computer, to complement the digital storage. Complement itself is positive, negative complement flag is in addition, other bits plus a bitwise.

Characteristics complement

1, a negative integer (or original code) and its complement (or complement) are added, and as the mold.
2, a complement integer is complemented and then, equal to the integer itself.
3, the positive and the negative zero zero complement representation same.

Measurement range from 0 to 23 clock, so the time the mold is equal to 24. Suppose the current point to the hour hand 17 points and the exact time is 9:00, the time adjustment can have the following two methods:
1. The inverted dial 8 hours, namely: 17--8 = 9;
2 cis Dial 16 hours: 17 + 16 = 33 ; 33% = 24 9
in this example, 16 -8 is represented in the 24's complement number. With 16 shows benefit-8 is a subtraction into addition.
If positive and negative numbers are represented, the computer needs to do addition and subtraction calculation processing different original code. And if you use complement representation, unified computing to the computer using the addition and subtraction calculation, reducing the burden on the computer.

 

The first example: the storage form 7 of
the original code
(1) 7 is positive, so the flag bit is 0
(2) The remaining 31 bits represent the digital portion: 000 0000 0000 0000 0,000,000,000,000,111
so the original code 7 is:
0000 0000 0000 0000 0000 0000 0000 0111

Complement
positive number with the complement as the original code, so that the form is stored in the computer 7 as follows:
0000 0000 0000 0000 0,000,000,000,000,111

A second example: a storage format -7
original code
(1) -7 is negative, the flag bit is 1
(2) represents the remaining 31 Part number: 000 0000 0000 0000 0000 0000 0000 0111
so that the original code -7 is:
1,000,000,000,000,000 0,000,000,000,000,111

Complement
negative complement is in addition to the flag, other bits plus a bitwise. Therefore -7 form stored in a computer as:
1,111,111,111,111,111 1,111,111,111,111,001

 

9 + 5 calculation
complement 9 is expressed as:
0000 0000 0000 0000 0,000,000,000,001,001
5 complement representation is:
0000 0000 0000 0000 0,000,000,000,000,101
two's complement addition, and the number of other than 32 removed:
0000 0000 0000 0000 0000 0000 0000 1110
obtain the results 14

Calculate a 9 -. 5
9's complement representation is:
0000 0000 0000 0000 0,000,000,000,001,001
-5 complement expressed as:
1,111,111,111,111,111 1,111,111,111,111,011
two's complement addition, and the number of other than 32 removed:
0000 0000 0000 0000 0,000,000,000,000,100
obtain results 4

 

Logical Operators

- (non-operator)

1. Features: unary operator,
2. rules: generating an input bit value of the opposite - if the input 0, output 1; if the input 1, the input 0
3. Case:
    int ~ A = 2; 
    the System.out. println (a); // result is 
4. analysis:
     binary complement of 2 is expressed as:
        00000000 00000000 0,000,000,000,000,010
     operation:
      ~ 00000000 00000000 0,000,000,000,000,010
    ------------------ ------------------------
         1,111,111,111,111,111 1,111,111,111,111,101 // the decimal corresponding to the complement: -3

application

1: ~ n = - (n + 1), for example: 1-3 = -4

2: Get integer n binary string last 1: -n & n = ~ (n-1) & n

3: 1 to remove the last of the binary string integer n: n & (n-1).

 

& (And operator)

1. Features: binary operator, two operations binary data; two binary least significant bit justified only when the two are only a number of bits is 1, otherwise 0
2. Case:
    int. 3 & A = 2; 
    System.out.println (a); // result is 2 
3. analysis:
    twos complement 3 is expressed as:
        00000000 00000000 0,000,000,000,000,011
    two's-complement representation of 2:
        00000000 00000000 0,000,000,000,000,010
    operations: 3 & 2 
        00000000 00000000 00000000 00000011
    & 00000000 00000000 0,000,000,000,000,010
    ------------------------------------------ -
        00000000 00000000 0,000,000,000,000,010 is binary 2  

application

Determining a number n of parity

n & 1 == 1 "odd":? "even"

Why can judge and 1 parity? The so-called binary 1 into 2 is full, so good, and the even the lowest level of certainty is 0 (just over 2, right?). Similarly, the lowest bit odd certainly 1.int type 1, the first 31 bits is 0, both 1 & 0 or 0 & 0 the result is 0 then 1 on the lowest bit difference is 1, and if n binary lowest bit is 1 (odd) and 1, and the result is 1, the anti result is 0.

int a = 8;
if (a % 2 == 0) {
    System.out.println("a是偶数");
} else {
    System.out.println("a是奇数");
}
if ((a & 0x1) == 0) {
    System.out.println("a是偶数");
} else {
    System.out.println("a是奇数");
}

 

Seeking a number of integer binary 1

Ideas: The integer n 1 and an AND operation, the least significant bit when the integer n is 1, the result is nonzero, 0 otherwise. 
1 then the left one, proceed with the operation and n, when the low times is 1, the result is nonzero, otherwise the result is 0. 
Operation cycles or more, the number of non-zero can be recorded. 
code show as below:

public class TestDemo {
	public static void main(String[] args) {
		int a = 7;
		int retNum = times1(a);
		System.out.println(retNum);
	}
	
    public static int times1(int n ){

        int count = 0;
        int flag = 1;
        while(flag <= n){
            if((n&flag) != 0)
                count++;
            flag = flag<<1;
        }
        return count;
    }
}

Output:

3

 

Optimized Method 
ideas: 
1. an integer n, such as 10, which is 1010 binary. 
2. Save 10 becomes a binary 9,9 is 1001. The 
binary comparator 10 and 3. 9, 10 to a subtraction operation is equivalent to a bit inversion of the least significant bit of binary 10 and back, and in front of the number unchanged. 
Summary: integer to a minus 1, and then to do with the original integer arithmetic, the integer will rightmost 1 a 1 to a 0. Then the binary representation of an integer in the number of 1, on how many times such an operation can be performed. Thus the number of comparisons can be reduced.

public class TestDemo {
	public static void main(String[] args) {
		int a = 7;
		int retNum = times2(a);
		System.out.println(retNum);
	}
	
    public static int times2(int n){
        int count = 0;
        while(n!=0){
            count++;
            n = n&(n-1);
        }
        return count;
    }
}

Output:

3

 

| (Or operator)

1. Features: binary operator, two operations binary data; two lowest binary bit aligned, when the number of bits of two as long as it is 1, a 1, otherwise 0
2. Case:
    int. 3 A = | 2; 
    System.out.println (a); // was 3. 
3. analysis:
    twos complement 3 is expressed as:
        00000000 00000000 0,000,000,000,000,011
    two's-complement representation of 2:
        00000000 00000000 0,000,000,000,000,010
    calculation: 3 | 2 
        00000000 00000000 00000011 00000000
    | 00000000 00000000 00000000 00000010
    ------------------------------------------ -
        00000000 00000000 0,000,000,000,000,011 corresponding to the complement of the decimal 3  

 

^ (Exclusive OR operator)

1. Features: binary operator, two operations binary data; two lowest binary bit aligned, when the number of bits of two as long as it is 1, a 1, otherwise 0
2. Case:
    int. 3 A = | 2; 
    System.out.println (a); // was 3. 
3. analysis:
    twos complement 3 is expressed as:
        00000000 00000000 0,000,000,000,000,011
    two's-complement representation of 2:
        00000000 00000000 0,000,000,000,000,010
    calculation: 3 | 2 
        00000000 00000000 00000011 00000000
    | 00000000 00000000 00000000 00000010
    ------------------------------------------ -
        00000000 00000000 0,000,000,000,000,011 corresponding to the complement of the decimal 3  
 

^ (Exclusive OR operator)

1. Features: binary operator, two operations binary data; two binary least significant bit justified only when the two pairs of digits are not simultaneously 1, 0 is the same
2. Case:
    int = A ^ 2. 3; 
    the System .out.println (a); // result is 1 
3. analysis:
    twos complement 3 is expressed as:
        00000000 00000000 0,000,000,000,000,011
    two's-complement representation of 2:
        00000000 00000000 0,000,000,000,000,010
    calculation: ^ 3 2 
        00000000 00000000 0,000,000,000,000,011
    ^ 00000000 00000000 0,000,000,000,000,010
    -------------------------------------------
        00000000 00000000 0,000,000,000,000,001 corresponding to the complement of a decimal 

application

Lowercase to uppercase, lowercase to uppercase (charArray [i] ^ = 32, as in the ASCII code, uppercase and lowercase letters worse 32, thus using the XOR operator, or by distinct 0 , binary form the original character of the other bits of the original value retained in the first six different or, if the original bit is 0 to 1, the original bit is 1 to 0):

public class TestDemo {
public static void main(String[] args) {
	String tempString = "1a2b3E5F6P7p";
	char [] charArray = tempString.toCharArray();
	for(int i = 0; i < charArray.length; i++)
	if(Character.isLetter(charArray[i])) charArray[i] ^= 32;
	System.out.println(String.valueOf(charArray)); // result is 1A2B3e5f6p7P
}
}

Output:

1A2B3e5f6p7P
 

No temporary variable swap two numbers

In int [] array of end-swap, is not seen this code:

public static int[] reverse(int[] nums){
            int i = 0;
            int j = nums.length-1;
            while(j>i){
                nums[i]= nums[i]^nums[j];
                nums[j] = nums[j]^nums[i];
                nums[i] = nums[i]^nums[j];
                j--;
                i++;
            }
            return nums;
        }

Three times using the XOR, and no temporary variables completed two digital switching, how to achieve it?


The above calculation mainly follows a formula: b ^ (a ^ b) = a.

We can do the above formula is derived as follows:

Any number of XOR result itself and there is 0. Theorem a ^ b = b ^ a. Or a heterologous sequence without operator, b ^ a ^ b = b ^ b ^ a, the result is 0 ^ a.

XOR calculation are listed in the table again:

Operation number 1

0

0

1

1

Operation number 2

0

1

0

1

Bitwise XOR

0

1

1

0

Can be found, having the characteristics of holding the exclusive-OR 0, and 1 XOR having inverted characteristics. These features may be performed using the operand fetch.

         Then 0 ^ a, or 0 has exclusive use of the characteristics of the holding, the final result is a.

In fact, XOR algorithm java in full compliance with the laws of mathematics calculation:

①    a ^ a =0

②    a ^ b =b ^ a

③    a ^b ^ c = a ^ (b ^ c) = (a ^ b) ^ c;

④ d = a ^ b ^ c can be introduced a = d ^ b ^ c.

⑤    a ^ b ^a = b.

 

<< (shift left operator)

0. form: m << n 
1. Features: binary operator, m-digit binary left shift of n bits of the result; equivalent results: m * (n-th power of 2)
2. Case:
    int. 3 A = < <2; 
    System.out.println (a); // result is 12 
3. analysis:
    twos complement 3 is expressed as:
        00000000 00000000 0,000,000,000,000,011

    Calculation: 3 << 2 
            00000000 00000000 0,000,000,000,000,011
    << 2    
    ------------------------------------- ------
            00000000 00000000 0,000,000,000,001,100 corresponding to the complement of a decimal 12 

application

M << n may be used to obtain the results, such as:

        System.out.println("2^3=" + (1<<3));//2^3=8

        System.out.println("3*2^3=" + (3<<3));//3*2^3=24

The results are not quite right yet? He insisted that if 2 << - 1 Why is not equal to 0.5, said earlier, only operand bit arithmetic is integer and character. When seeking the minimum int can represent, may be used

// commemorating

System.out.println(1 << 31);

System.out.println(1 << -1);

31 can be found in the left and the results obtained -1 position is the same, the same way, the left and left 30 -2 obtained the same result. Move a bit negative, it is not equal to the absolute value of the negative position to the right of it? Output will be able to find what it is not. Java int maximum value can be represented in 31-bit, 32-bit plus sign bit total. Here you can have such a displacement law:

Rule one: Any number of left (right) 32-bit multiplier is equal to the number itself.

Rule two: shift operations in the calculation of m << n, if n is a positive number, the actual number of bits of a mobile n% 32, if n is negative, then the number of bits actually moved to (32 + n% 32) , right, empathy.

Is left by a power of 2, corresponding to the right is divided by a power of two.

 

>> (right shift operator)

0. form: m >> n 
1. Features: binary operator, m-digit binary n-bit result of moving to the right; the result is equivalent to: m / (n-th power of 2) result rounded up
2. Case:
    a 3 >> 2 = int; 
    System.out.println (a); // result is 0 
3. analysis:
    twos complement 3 is expressed as:
        00000000 00000000 0,000,000,000,000,011

    Calculation: 3 >> 2 
            00000000 00000000 0,000,000,000,000,011
    >> 2    
    ------------------------------------- ------
            00000000 00000000 00000000 00000000 corresponding to the complement of decimal 0
4. Note: the last two 11 moves to the right, on the left side just make up 0; so the result is 0             

 

>>> (unsigned right shift operator)

1. Binary operators
2. Features: it is extended with 0, regardless of the sign bit are zero with the highest 
3. Case:
    int. 3 >>> A = 2; 
    System.out.println (A); // results 0 
4. analysis:
    twos complement 3 is expressed as:
        00000000 00000000 0,000,000,000,000,011
    operation:
        00000000 00000000 0,000,000,000,000,011
    >>> 2
    ----------------------- -------------------
        00000000 00000000 00000000 00000000 

Applications absolute value

public class TestDemo {
public static void main(String[] args) {
int a = -3;
System.out.println(abs(a));
}

public static int abs(int val) {
    // 看上去是够累的
    return (((val & (~0 << 31)) >>> 31) == 1) ? ((~val) + 1) & (~(~0 << 31)) : val;
}
}

Output:

3

Absolute value

(a^(a>>31))-(a>>31)

To sort out the idea of ​​using the absolute value of bit operation: If a is a positive number, remain unchanged, with the need to maintain the characteristics of the exclusive-OR 0; if a is negative, then the complement of the inverted every source +1 seeking the first source, and then inverted complement each -1, required in this case has an inverted XOR characteristics.

31 right after any positive number only sign bit 0, the final result is 0, the sign bit only after a 31, 31 truncate any overflow right negative, fill the vacated 31 1 symbol bits, the final result is -1. 31 right shift operation may be made of any symbol bit integer.

So comprehensive step above formula can be obtained. a >> 31 made of a symbol, if a is a positive number, a >> 31 is equal to 0, a ^ 0 = a, unchanged; if a is negative, a >> 31 is equal to -1, a ^ -1 inverted every a.

 

Bitwise addition

A ^ b available from the press without carry bits and sum;

A & b by the available bits may be generated into place;

<< 1 value obtained by a carry (a & b).

Then in situ and by adding the bit carry and + is the addition and, while a ^ b + (a & b) << 1 + corresponds to both sides and then substituted into the above three steps addition calculation. Until the carry is 0 and the carry is not described at this time, i.e., in situ and are summed.

public class TestDemo {
public static void main(String[] args) {
int a = -3;
int b = 1;
System.out.println(add(a,b));
}

public static int add(int a,int b) {
    int res=a;
    int xor=a^b;//得到原位和
    int forward=(a&b)<<1;//得到进位和
    if(forward!=0){//若进位和不为0,则递归求原位和+进位和
        res=add(xor, forward);
    }else{
        res=xor;//若进位和为0,则此时原位和为所求和
    }
    return res;                
}
}

Output:

-2

 

Bit arithmetic subtraction

Subtraction: ab

A -b = + (- b), ~ (b-1) = - b can be obtained ab = a + (- b) = a + (~ (b-1)). The subtraction can be converted to the adder.

public class TestDemo {
public static void main(String[] args) {
int a = -3;
int b = 1;
System.out.println(minus(a,b));
}

public static int add(int a,int b) {
    int res=a;
    int xor=a^b;//得到原位和
    int forward=(a&b)<<1;//得到进位和
    if(forward!=0){//若进位和不为0,则递归求原位和+进位和
        res=add(xor, forward);
    }else{
        res=xor;//若进位和为0,则此时原位和为所求和
    }
    return res;                
}

public static int minus(int a,int b) {
        int B=~(b-1);
        return add(a, B);        
    }
}

Output:

-4

 

Bit multiplication operation

Multiplication: a * b

Binary multiplication first look at how it is done:

(1011 << 1, multiplied by the equivalent of 0010)  
(1011 << 3, corresponding to multiplying by 1000)  

It can be seen binary multiplication principle is: from low to high multiplier, and this encounter 1 1 right from the first multiplier i (i 0 Number of starting) position, then put the multiplicand left i bit to get temp_i. Until after traversing the multiplier 1, the multiplicand left values ​​are obtained according to you 1 temp_i add up to obtain the multiplication result. Then according to this principle, the code can be achieved: Important here is: i recording multiplier bits with the current traversal, the current bit of a multiplicand bit and i is added to the left and, at the same time a process i ++; is 0 multiplier right, i ++, under a deal with multiplier == 0 Description ...... until the multiplier 1 traverse over. At this point you can return to and.

public class TestDemo {
public static void main(String[] args) {
int a = -3;
int b = 2;
System.out.println(multi(a,b));
}

public static int multi(int a,int b){
    int i=0;
    int res=0;
    while(b!=0){//乘数为0则结束
        //处理乘数当前位
        if((b&1)==1){
            res+=(a<<i);
            b=b>>1;
            ++i;//i记录当前位是第几位
        }else{
            b=b>>1;
            ++i;
        }
    }
    return res;
}
}

Output:

-6

 

Bitwise division

Division: a / b

Meaning the division lies: how many of you can find a composition b. So therefore realize that we can get the division: minus can find a number of b, the number of subtraction is done quotient of the division.

public class TestDemo {
public static void main(String[] args) {
int a = 6;
int b = 2;
System.out.println(sub(a,b));
}

public static int sub(int a,int b) {
    int res=-1;
    if(a<b){
        return 0;
    }else{
        res=sub(minus(a, b), b)+1;
    }
    return res;
}
public static int minus(int a,int b) {
    int B=~(b-1);
    return add(a, B);        
}
public static int add(int a,int b) {
    int res=a;
    int xor=a^b;//得到原位和
    int forward=(a&b)<<1;//得到进位和
    if(forward!=0){//若进位和不为0,则递归求原位和+进位和
        res=add(xor, forward);
    }else{
        res=xor;//若进位和为0,则此时原位和为所求和
    }
    return res;                
}
}

Output:

3

 

Mathematical basis

About the number 12 include: 1,2,3,4,6,12. A total of six

Can a number divisible by another number, this number is the number of other divisors . Such as 2,3,4,6 can be divisible by 12, 12 are therefore 2,3,4,6 divisor . Also known as factor.

Count the number of divisors

public class TestDemo { 
    public static void main(String[] args) {
        int count = 0;
        int n = 12;
        for(int i = 1;i <= n;i++) {
            if(n % i == 0)
                count++;
        }
        System.out.println(count);
    }
}

Output:

6

 

Prime number is defined as a natural number greater than 1, in addition to 1 and no other factor itself.

The output of all the prime numbers

public class TestDemo {
	public static void main(String[] args) {
		boolean flag = false;
		for (int i = 2; i <= 10; i++) {
			for (int j = 2; j * j < i; j++) {
				if (i % j == 0) {
					flag = true;
					break;
				}
			}
			if (flag == false) {
				System.out.println(i);
			}
			flag = false;
		}
	}
}

Output:

2
3
4
5
7
9

Number engagement means can be a natural number, in addition to a whole and excluding itself, but also by other numbers (except for 0) divisible. Contrast is a prime number, but neither 1 nor prime numbers together . Minimum composite number is 4.

Ideas (minus the number of digits of prime numbers between 100-1000 so-called composite number)

The number of output composite number

public class TestDemo {
	public static void main(String[] args) {
		int a = 0;
		int b = 0;

		for (int i = 100; i <= 1000; i++) {
			a++;
			boolean d = true;
			for (int j = i / 2 + 1; j > 1; j--) {
				if (i % j == 0) {
					d = false;
				}
			}
			if (d == true) {
				b++;
			}
		}
		int c = a - b;
		System.out.println(c);
	}
}

Output:

758
 

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_35029061/article/details/92529240