Offer to prove safety forty-seven / Eight: beg 1 + 2 + 3 + ...... + n sum and do not do addition subtraction multiplication and division

Casual working

Seeking 1 + 2 + 3 + ... + n, requires multiplication and division can not be used, for, while, if, else, switch, case and keywords such as conditional statement (A B:? C)

Thinking

We usually think about is how to take advantage of if adding digital loop to achieve, where we use to achieve short-circuited when the exit condition is not met in time.

Code

 public int Sum_Solution(int n) {
   int sum=n;
        boolean t=(n>0)&&(sum=sum+Sum_Solution(n-1))>0;
        return sum;
    }

Casual working

A write function, and the sum of two integers, the function may not be used in vivo requires +, -, *, / four arithmetic symbols.

Thinking

Calculated using the & ^

First look at is how to do decimal: 5 + 7 = 12, three steps
Step one: Members of adding value, not carry, get 2.
Step Two: carry value is calculated, this step to give 10. If the carry is 0, then the value from the first step is the final result.

The third step: repeating the above two steps, but the added value becomes a result of the two steps 10 and 2 obtained, to give 12.

Similarly, we can use a three-step way to calculate the sum of the binary value:
5-101,7-111
first step: adding the value of everybody, not carry, get 010, equivalent to the sum of each binary you do different or operation, 101 ^ 111.

Step Two: carry value calculated to give 1010 corresponds to the operation do you get 101, left again to give a 1010 (101 & 111) << 1.

Repeating the above two steps a third step, you are added 010 ^ 1010 = 1000, feed = bit value 100 (010 & 1010) << 1.
Continue repeating the above two steps: 1000 ^ 100 = 1100, the carry is 0, out of the loop 1100 as the final result.

Code

 public int Add(int num1,int num2) {
        while(num2!=0){
            int temp=num1^num2;
             num2=(num1&num2) <<1;
            num1=temp;
        }
        return num1;
    }
Published 70 original articles · won praise 49 · views 6835

Guess you like

Origin blog.csdn.net/weixin_44015043/article/details/105393868