算法总结:数与位

数与位
题目分类 题目编号
数字的位操作 7、9、479、564、231、342、326、504、263 190、191、476、461、477、693、393、172、458、258、319、405、171、168、670
数学题:233、357、400、492、29、507
快速幂 50、372

大神笔记

1.数字的操作

7. Reverse Integer
如果rev * 10的时候出界,那么就return 0
即:rev * 10>Integer.MAX_VALUE;
如果 rev * 10==Integer.MAX_VALUE,是valid,
但rev == Integer.MAX_VALUE / 10 && pop > 7就出界了

rev * 10<Integer.MIN_VALUE
rev * 10 == Integer.MIN_VALUE;

如果 rev * 10 == Integer.MIN_VALUE,是valid,

但rev == Integer.MIN_VALUE / 10 && pop < -8就出界了

class Solution {
    public int reverse(int x) {
        int rev = 0;
        while (x != 0) {
            int pop = x % 10; //-123: pop=-3
            x /= 10;
            if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
            if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
            rev = rev * 10 + pop; //pop=-3
        }
        return rev;
    }
}

9. Palindrome Number
技巧:从一个integer中分解出数字来。
123%10=3—>分解出3
123/10=12
12%10=2—>分解出2
12/10=1
1%10=1—>分解出1
classic isPalindrome:
long t = x将原传入的值拷贝一份。
t/10修改的是t的值,
最后对比 return rev == x;时x仍为原来的值。

	boolean isPalindrome(long x) {//123
        long t = x, rev = 0;
        while (t > 0) {
            rev = 10 * rev + t % 10;//321
            t /= 10;
        }
        return rev == x;
    }
public class Solution {
    public boolean isPalindrome(int x) {
        // Special cases:
        // As discussed above, when x < 0, x is not a palindrome.
        // Also if the last digit of the number is 0, in order to be a palindrome,
        // the first digit of the number also needs to be 0.
        // Only 0 satisfy this property.
        if(x < 0 || (x % 10 == 0 && x != 0)) {
            return false;
        }

        int revertedNumber = 0;
        while(x > revertedNumber) {
            revertedNumber = revertedNumber * 10 + x % 10;
            x /= 10;
        }
        // When the length is an odd number, we can get rid of the middle digit by revertedNumber/10
        // For example:input is 12321, at the end of the while loop we get x = 12, revertedNumber = 123,
        // since the middle digit doesn't matter in palidrome(it will always equal to itself), we can simply get rid of it.
        return x == revertedNumber || x == revertedNumber/10;
    }
}

Time complexity : divided the input by 10 for every iteration, so the time complexity is : O(log10(n)).
Space complexity : O(1).

479. Largest Palindrome Product

在这里插入代码片

2.数字的位运算:

程序中的所有数在计算机内存中都是以二进制的形式储存的。位运算说穿了,就是直接对整数在内存中的二进制位进行操作。

6的二进制是110,11的二进制是1011,那么6 & 11的结果就是2,它是二进制对应位进行逻辑运算的结果(0表示False,1表示True,空位都当0处理):
110
AND 1011
———
0010 –> 2

=== 1. and运算 === 符号:&
and运算通常用于二进制取位操作,例如一个数 and 1的结果就是取二进制的最末位。这可以用来判断一个整数的奇偶,二进制的最末位为0表示该数为偶数,最末位为1表示该数为奇数.

=== 2. or运算 === 符号:|
or运算通常用于二进制特定位上的无条件赋值,例如一个数or 1的结果就是把二进制最末位强行变成1。如果需要把二进制最末位变成0,对这个数or 1之后再减一就可以了,其实际意义就是把这个数强行变成最接近的偶数。

=== 3. xor运算 ===  符号:^
xor运算通常用于对二进制的特定一位进行取反操作,因为异或可以这样定义:0和1,**异或0都不变**,**异或1则取反**。(相同取0,不同取1)
xor运算的逆运算是它本身,也就是说两次异或同一个数最后结果不变,即(a xor b) xor b = a。xor运算可以用于简单的加密,比如我想对我MM说1314520,但怕别人知道,于是双方约定拿我的生日19880516作为密钥。1314520 xor 19880516 = 20665500,我就把20665500告诉MM。MM再次计算20665500 xor 19880516的值,得到1314520,于是她就明白了我的企图。

=== 4. not运算 === 符号:~
not运算的定义是把内存中的0和1全部取反。使用not运算时要格外小心,你需要注意整数类型有没有符号。如果not的对象是无符号整数(不能表示负数),那么得到的值就是它与该类型上界的差,因为无符号类型的数是用$0000到$FFFF依次表示的。下面的两个程序(仅语言不同)均返回65435。

=== 5. shl运算 === 符号:<<
a shl b就表示把a转为二进制后左移b位(在后面添b个0)。例如100的二进制为1100100,而110010000转成十进制是400,那么100 shl 2 = 400。可以看出,a shl b的值实际上就是a乘以2的b次方,因为在二进制数后添一个0就相当于该数乘以2。
通常认为a shl 1比a * 2更快,因为前者是更底层一些的操作。因此程序中乘以2的操作请尽量用左移一位来代替。
定义一些常量可能会用到shl运算。你可以方便地用1 shl 16 – 1来表示65535。很多算法和数据结构要求数据规模必须是2的幂,此时可以用shl来定义Max_N等常量。

=== 6. shr运算 === 符号:>>
和shl相似,a shr b表示二进制右移b位(去掉末b位),相当于a除以2的b次方(取整)。我们也经常用shr 1来代替div 2,比如二分查找、堆的插入操作等等。想办法用shr代替除法运算可以使程序效率大大提高。最大公约数的二进制算法用除以2操作来代替慢得出奇的mod运算,效率可以提高60%。

============

一些常见的二进制位的变换操作。
功能 | 示例 | 位运算
———————-+—————————+——————–
去掉最后一位 | (101101->10110) | x shr 1
在最后加一个0 | (101101->1011010) | x shl 1
在最后加一个1 | (101101->1011011) | x shl 1+1
把最后一位变成1 | (101100->101101) | x or 1
把最后一位变成0 | (101101->101100) | x or 1-1
最后一位取反 | (101101->101100) | x xor 1
把右数第k位变成1 | (101001->101101,k=3) | x or (1 shl (k-1))
把右数第k位变成0 | (101101->101001,k=3) | x and not (1 shl (k-1))
右数第k位取反 | (101001->101101,k=3) | x xor (1 shl (k-1))
取末三位 | (1101101->101) | x and 7
取末k位 | (1101101->1101,k=5) | x and ((1 shl k)-1)
取右数第k位 | (1101101->1,k=4) | x shr (k-1) and 1
把末k位变成1 | (101001->101111,k=4) | x or ((1 shl k)-1)
末k位取反 | (101001->100110,k=4) | x xor ((1 shl k)-1)
把右边连续的1变成0 | (100101111->100100000) | x and (x+1)
把右起第一个0变成1 | (100101111->100111111) | x or (x+1)
把右边连续的0变成1 | (11011000->11011111) | x or (x-1)
取右边连续的1 | (100101111->1111) | (x xor (x+1)) shr 1
去掉右起第一个1的左边 | (100101000->1000) | x and (x xor (x-1))

public class BitOperation {
    public static void main(String[] args) {
        //0001-->0000 去掉最后一位  |1-->0
        System.out.println(1>>1);
        //0011-->0110 在最后加一个0  |3-->6
        System.out.println(3<<1);
        //0011-->00111 在最后加一个1   |  3-->7
        System.out.println((3<<1)+1);
        //System.out.println((3<<1)+1);//12
        //0010-->0011把最后一位变成1  |  2-->3
        System.out.println(2 | 1);
        //0011-->0010把最后一位变成0   |  3-->2
        System.out.println((3|1 )-1);
        //0011-->0010 最后一位取反  |  3-->2
        System.out.println(3^1);
        //把右数第k位变成1    k==3
        //0010-->0110  | 2-->6
        int k=3;
        System.out.println(2 | (1<<k-1));
        //把右数第k位变成0
        //1001-->0001 |  9-->1
        int k2=4;
        System.out.println(9 & ~(1<<k2-1));
        //System.out.println(9 & (0<<k2-1));  -->0 ???
        //右数第k位取反  xor 取反
        //8421
        //1001-->0001 |   9-->1
        int k3=4;
        System.out.println(9 ^ (1<<k3-1));
        //取末三位 1101------->101  |   13-->5
        //1101 & 0111 后三位&1保留
        System.out.println(13 & 7);
        //取末k位  29--->13
        // (11101->1101,k=4)       | x and ((1 shl k)-1))
        int m2=4;
        System.out.println("取末k位: "+(29 & ((1<<m2)-1)));
        //取右数第k位  01101-> 1  |  13-> 1
        //00101-> 0  |  7--> 0
        int m=4;
        System.out.println(7 >> (m-1) & 1);
        //把末k位变成1 (01001->01111,k=4)      | x or (1 shl k-1)
        //9-->15
        int n=4;
        System.out.println("把末k位变成1 : " + (9 | (1<< n)-1));
        //末k位取反  ^1   k=3  | x xor ((1 shl k)-1)
        //01001--->01110  | 9-->14
        System.out.println(9^ (1<<k)-1);
        //把右边连续的1变成0
        //     32 16 8 4 2 1  47-->32
        //(    1  0  1 1 1 1-> 1 0 0 0 0 0)    | x and (x+1)
        // +1: 1  1  0 0 0 0
        System.out.println(47 & (47+1));
        //把右起第一个0变成1    |   (101111->111111)    | x or (x+1)
        //                 // +1: 110000
        System.out.println("把右起第一个0变成1: " + (47 | (47+1)));
        //把右边连续的0变成1
        //   1 0 1 0 0 0-->1 0 1 1 1 1  40-->47
        //-1:1 0 0 1 1 1
        System.out.println(40 | (40-1));
        //取右边连续的1     (101111->1111)   47-->15      | (x xor (x+1)) shr 1
        //        +1:  xor 1  1  0 0 0 0-->0 1 1 1 1 1
        //    10101111
        //xor 10110000
        //    00011111  相同取0,不同取1
        System.out.println("取右边连续的1: "+ ((47 ^ (47+1))>>1) );
        //去掉右起第一个1的左边   (100101000->1000)  | x and (x xor (x-1))
        //268421
        //   101000 -->  1000
        //-1:100111
        //^: 001111
        //&: 001000
        System.out.println( 40 & (40 ^ (40-1)));
    }
}

190. Reverse Bits
Question: 什么时候需要变成Long?
是因为怕左移动时overflow?

Question: 为什么primitive变量会被认为是immutable?
实际上,对immutable的定义,更强调一种对本体的认知。假设一个人是一个对象,人的头发是他的一个成员变量,对这个头发的修改并不会导致从一个人变成了另一个人。而考虑int等primitive变量,我们在修改它的值的时候,实际上相当于对该变量本体的认知。将该值修改,整个int就变成了另一个int,就像整个人变成了另一个人,也因此认为对primitive变量的修改,是完全的“换了一个东西”。 原文链接:
下面解法中,每次swap操作完n变成了“另外一个人”。
要将swap的结果存一下,重新赋值给n变量。否则下一次swap的n,仍然是最初传进来的n。
算法中经常使用int res作为全局变量,会在每一步的操作中被改变成“另外一个人”,无法通过reference指针找到这个结果。所以需要改成res[0],在array上改来改去,并总能通过固定的指针找到结果。
Question:什么是signed什么是unsigned?
Unsigned variables, such as unsigned integers, will only allow you to represent numbers in the positive.
————————————————

public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
	  int i=0;
	  int j=31;
	  while(i<j){
	      n=swap(n,i,j);//primitive type pass by value,要将swap的结果存一下
	      i++;
	      j--;
	   }
	   return n;
	 }

  private int swap(int n, int i, int j){
    int bi=(n>>i)&1; //prefer to use "n >> i & 1L", 简单地去除了可能的歧义和增加了可读性。
    int bj=(n>>j)&1;//bi和bj取出来一下
    if(bi!=bj){
        n^=((1<<i)+(1<<j));// 和 特定两位 异或1,
    }
    return n;
  }
}
/*
public long swap(long n, int i, int j){
    return ((1L << i) | (1L << j)) ^ n; // 这里要把左边的放进括号
 }
 & ^
*/

BinaryGap
A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.

Write a function:
class Solution { public int solution(int N); }

public class BinaryGap {
    public int binaryGap(int N){
        if(N<=0) return 0;
        //43210
        //000010000010001
        //              1
        int maxZero=0;
        int oneCount=0;
        int zeroCount=0;
        for(int i=0;i<=31;i++){//32 bits, move to right 31 times
            if(((N>>i) & 1)==1) { //
                oneCount++;
            }
            if(oneCount>=1){
                if(((N>>i) & 1)==0){
                    zeroCount++;
                }
                if(((N>>i) & 1)==1){
                    maxZero=Math.max(maxZero,zeroCount);
                    zeroCount=0;
                }
            }
        }
        return maxZero;
    }
    //For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.
    public static void main(String[] args) {
        BinaryGap b=new BinaryGap();
        int N=1041;
        System.out.println(b.binaryGap(N));
        int N2=32;
        System.out.println(b.binaryGap(N2));
        int N3=9;
        System.out.println(b.binaryGap(N3));
        int N4=529;
        System.out.println(b.binaryGap(N4));
    }
}

564. Find the Closest Palindrome

技巧:虽然这个写法TLE了,但+1-1两头试的写法值得借鉴。

for (long i = 1;; i++) {
– if (isPalindrome(num - i))
return “” + (num - i);
– if (isPalindrome(num + i))
return “” + (num + i);
}

public class Solution {
    public String nearestPalindromic(String n) {
        long num = Long.parseLong(n);//Integer.valueOf(n);
        for (long i = 1;; i++) {
            if (isPalindrome(num - i))
                return "" + (num - i);
            if (isPalindrome(num + i))
                return "" + (num + i);
        }
    }
    boolean isPalindrome(long x) {
        long t = x, rev = 0;
        while (t > 0) {
            rev = 10 * rev + t % 10;
            t /= 10;
        }
        return rev == x;
    }
}

231. Power of Two
method1:Power of **,技巧:如果除得尽,就一直除
method2: 技巧:
0100肯定是Power of Two
0010肯定是Power of Two
0001肯定是Power of Two
只要其中只有一个1

class Solution {
    public boolean isPowerOfTwo(int n) {
        if (n == 0) return false;
        long x=(long) n;
        int count=0;
         while (x>0){
            if((x & 1)==1){
                count++;
            }
            x=x>>1;
        }
           return count==1;
    }
}

技巧:
数字8: 1000
数字7: 0111
如果数字中只有一个1,那么&操作之后,就为0!

  public boolean isPowerOfTwo(int number) {
    //method2
    //number-1
    //01000
    //-1
    //00111
    return (number>0) && ((number-1) & number)==0;
  }

342. Power of Four
method1:Power of **,技巧:如果除得尽,就一直除
method2:
0xaaaaaaaa
1010 1010 1010 1010 1010 1010 1010 1010
&
0000 0000 0000 0001
0000 0000 0000 0100
0000 0000 0001 0000
0000 0000 0100 0000
。。。往前挪两位*4都可以。

    public boolean isPowerOfFour(int num) {
      return (num > 0) && ((num & (num - 1)) == 0) && ((num & 0xaaaaaaaa) == 0);
    }
    public boolean isPowerOfFour(int num) {
      if (num == 0) return false;
      while(num%4==0){
          num/=4;
      }
        return num==1;
    }

326. Power of Three
method1:Power of **,技巧:如果除得尽,就一直除

    public boolean isPowerOfThree(int n) {
        if(n<1) return false;
       while(n%3==0){//如果除得尽,就一直除
           n/=3;
       }
        //check the last one is 1 or not.
        return n==1;
    }

504. Base 7
7进制的,
/7
%7

class Solution {
    public String convertToBase7(int num) {
        //100/7=14...2
        //14/7=2...0
        //2/7....2
        if(num==0) return 0+"";
        int num2=Math.abs(num);
        StringBuilder sb=new StringBuilder();
        int mod;
        while(num2>0){
            mod=num2%7;
            num2=num2/7;
            sb.insert(0,mod);
        }
        if(num<0){
            sb.insert(0,"-");
        }
        return sb.toString(); 
        //return sb.reverse().toString(); 
    }
}

263. Ugly Number

public boolean isUgly(int num) {
        if(num<=0) return false;
        if(num==1) return true;
        while(num%2==0){
            num/=2;
        }
        while(num%3==0){
            num/=3;
        }
        while(num%5==0){
            num/=5;
        }
        return num==1;
    }
while(num>1){
        if(num%2==0 || num%3==0 || num%5==0){
            if(num%2==0){
                num=num/2;
            }
            if(num%3==0){
                num=num/3;
            }
            if(num%5==0){
                num=num/5;
            }
        }else{
            return false;
        }
    }
    return true;
}

191. Number of 1 Bits
不断左移mask
mask <<= 1;

public int hammingWeight(int n) {
        int count=0;
        int mask = 1;
        for (int i = 0; i < 32; i++) {
            if ((n & mask) != 0) {
                 count++;
            }
            mask <<= 1;
        }
        return count;
    }

不断右移n:
n>>i

    public int hammingWeight(int n) {
        //unsigned integer ===positive
        int count=0;
        for(int i=0;i<32;i++){
            if(((n>>i)&1)==1){
                count++;
            }
        }
        return count;
    }

476. Number Complement
e.g. The binary representation of 5 is 101 (no leading zero bits), and its complement is 010.
把1送到左侧每个位置上,异或取反
num^= (1<<(pos-1));

    public int findComplement(int num) {
       // int pos=Integer.highestOneBit(num);
        int pos = (int)( Math.log(num) / Math.log(2) ) + 1;
        while(pos>0){
            num^= (1<<(pos-1));
            pos--;
        }
        return num;
    }

461. Hamming Distance
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)

  public int hammingDistance(int x, int y) {
    int xor = x ^ y;
    int distance = 0;
    while (xor != 0) {
      if (xor % 2 == 1){
        distance += 1;
      }
      xor = xor >> 1;
    }
    return distance;
  }

477. Total Hamming Distance
huahua
遍历每个数,数所有的数在31个位置上的1
那么剩下的就是0
例如10个数,每一位上,1有4个,0有6个,那么区别的个数为24

public int totalHammingDistance(int[] nums) {
        // counting of bit 1 for i-th least significant bit
        int[] cnt = new int[31];
        for (int num : nums) {
            for (int i = 0; i < 31; i++) {
                cnt[i] += (num >> i) & 1;
            }
        }
        // multiplies of every position
        int ans = 0;
        for (int k = 0; k < 31; k++) {
            ans += cnt[k] * (nums.length - cnt[k]);
        }
        return ans;
    }

693. Binary Number with Alternating Bits

class Solution {
    public boolean hasAlternatingBits(int n) {
       //get the last bit and the rest of the bits via n % 2 and n // 2
      int cur = n % 2;
        n /= 2;
        while (n > 0) {
            if (cur == n % 2) return false;
            cur = n % 2;
            n /= 2;
        }
        return true;
    }
}

393. UTF-8 Validation
huahua

在这里插入代码片

268. Missing Number

class Solution {
    public int missingNumber(int[] nums) {
        int[] newArr=new int[nums.length+1];
        for(int i=0;i<newArr.length;i++){
            newArr[i]=i;
        }
        
        int xor=0;
        for(int i=0;i<newArr.length;i++){
            xor^=newArr[i];
        }
        
        for(int i=0;i<nums.length;i++){
            xor^=nums[i];
        }
        return xor;
    }
}
    public int missingNumber(int[] nums) {
        int xor=nums.length; //01245     xor=5
        
        for(int i=0;i<nums.length;i++){
            xor^=i^nums[i];  //5^0^1^2^3^4 ^  {0,1,2,4,5}
        }
        
        return xor;
    }

458. Poor Pigs
hard

在这里插入代码片

258. Add Digits

class Solution {
    public int addDigits(int num) {
        int res=0;
        while(num>0){    
            res+=num%10;//38--> 8 ,3 
            num/=10; //num=0
             
            if(num==0 && res>9){ //res=11
                num=res;//11 continue
                res=0;//reset res
            }
        }
        return res;
    }
}

神奇
// 10=9⋅1+1
// 100=99+1=9⋅11+1
// 1000=999+1=9⋅111+1

class Solution {
    public int addDigits(int num) {
        if (num == 0) return 0;
        if (num % 9 == 0) return 9;
        return num % 9;
    }
}

319. Bulb Switcher
神奇

class Solution {
//The number of times we toggle a bulb is the total number of factors it has. If we toggle a bulb an odd number of times, it would stay on and only perfect squares have odd number of factors. So the result is the squareroot of the closest perfect square to less than or equal to n.
    public int bulbSwitch(int n) {
        return (int)Math.sqrt(n);
    }  
}

405. Convert a Number to Hexadecimal
四位四位对应转

class Solution {
    public String toHex(int num) {
        if (num == 0)
            return "0";
        char [] possibility = new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        StringBuilder sb = new StringBuilder();
        while (num != 0) {
            sb.append(possibility[num & 15]);
            num = (num >>> 4);
            //System.out.println(num);
            //26--->
            //16 8421
            // 1 1010
        }
        return sb.reverse().toString();
    }
}

171. Excel Sheet Column Number

26进制

    public int titleToNumber(String s) {
        int res=0;
        for(int i=0;i<s.length();i++){
            res=res*26+(s.charAt(i)-'A'+1);
        }
        return res;
    }

168. Excel Sheet Column Title
26 -> Z
27 -> AA
28 -> AB

    public String convertToTitle(int n) {
       if(n<=26) return ""+(char)(n-1+65);
        StringBuilder sb=new StringBuilder();
         
        while(n>0){
            n--;//27-->26  
            int remain=n%26; // 0-->'A‘
            sb.append(""+(char)(remain+'A'));
            n/=26;  //1-->0-->'A‘
        }
       
        return sb.reverse().toString();
    }

670. Maximum Swap

在这里插入代码片

2.数学题
Given an integer n, return the number of trailing zeroes in n!
例如10:
12345---->其中有1个10
678910—>其中有2个10
172. Factorial Trailing Zeroes

    public int trailingZeroes(int n) {    
        int zeroCount = 0;
        for (int i = 5; i <= n; i += 5) {
            int currentFactor = i;
            while (currentFactor % 5 == 0) {
                zeroCount++;
                currentFactor /= 5;
            }
        }
        return zeroCount;
    }

492. Construct the Rectangle

class Solution {
    public int[] constructRectangle(int area) {
        int res[]= new int[2];
       for(int i=1;i<=Math.sqrt(area);i++){
            if((area/i)>=i && (area%i==0)){
                res[0]=area/i;
                res[1]=i;  //随着i走到一半,越来越接近平方根。
            }
        }
        return res;
    }
}

29. Divide Two Integers
怎么处理Integer.MIN_VALUE
为什么?
if(dividend==-2147483648 && divisor==-1) return 2147483647;
max最多只到 2147483647,这里会得到-2147483648,显然不对。
需要手动得到2147483647

class Solution {
    public int divide(int dividend, int divisor) {
// Count the number of negatives + convert parameters to positives.  
    if(dividend==-2147483648 && divisor==-1) return 2147483647; //??
    int negatives = 0;
    if (dividend < 0) {
        negatives++;
        dividend = -dividend;
    }
    if (divisor < 0) {
        negatives++;
        divisor = -divisor;
    }

    // Count the number of subtractions.
    int subtractions = 0;
    while (dividend - divisor >= 0) {
        subtractions++;
        dividend -= divisor;
    }

    // Convert back to negative if needed.
    if (negatives == 1) {
        subtractions = -subtractions;
    }

    return subtractions;
    }
}

怎么处理Integer.MIN_VALUE
为什么?

	public static void main(String[] args) {
        int dividend=(-2147483648);
        int divisor=(-1);
        System.out.println(dividend/divisor);  //-2147483648

        int dividend1=(-2147483647);
        int divisor1=(-1);
        System.out.println(dividend1/divisor1);  //2147483647
    }

507. Perfect Number

class Solution { 
    public boolean checkPerfectNumber(int num) {
        if (num <= 0) {
            return false;
        }
        int sum = 0;
        for (int i = 1; i * i <= num; i++) {  //  <5
            if (num % i == 0) {  //28: i=1,2,4
                sum += i;
                if (i * i != num) {
                    sum += num / i; // +28,14,4
                }
            }
        }
        return sum - num == num;//-28
    }
}

3.快速幂

50. Pow(x, n)

class Solution {
    private double fastPow(double x, long n) {
        if (n == 0) {
            return 1.0;
        }
        double half = fastPow(x, n / 2);
        if (n % 2 == 0) {
            return half * half;
        } else {
            return half * half * x;
        }
    }
    public double myPow(double x, int n) {
        long N = n;
        if (N < 0) {  // 2^ (-2)  --->  (1/2)^2
            x = 1 / x;
            N = -N;
        }

        return fastPow(x, N);
    }
}

372. Super Pow
https://blog.csdn.net/beyond702/article/details/53222077
思路: 需要用到的数学知识

  1. a^b % 1337 = (a%1337)^b % 1337

  2. xy % 1337 = ((x%1337) * (y%1337)) % 1337, 其中xy是一个数字如:45, 98等等

其中第一个公式可以用来削减a的值, 第二个公式可以将数组一位位的计算, 比如 12345^678, 首先12345可以先除余1337, 设结果为X, 则原式就可以化为:

X^678 = ((X^670 % 1337) * (X^8 % 1337)) % 1337 = (pow((X^670 % 1337), 10) * (X^8 % 1337)) % 1337

在上面我用了一个pow来化简表示 X^670 = pow(X^670, 10), 当然不是库函数里面pow, 因为会超出界限, 因此我们需要自己在写一个pow来一个个的边乘边除余.

public int superPow(int a, int[] b) {
        int mod = 1337;
        int len = b.length;
        long res = 1;
        long base = a;
        for(int i=len-1; i>=0; i--){
            int cur = b[i];
            long local = 1;
            while(cur>0){
                local = (local*base)%mod;
                cur--;//?
            }
            res = (res*local)%mod;
            long nextbase = 1;
            for(int c=0; c<10; c++)
                nextbase = (nextbase*base)%mod;
            base = nextbase;
        }
        return (int)res;
    }

1823. Find the Winner of the Circular Game

class Solution {
    public int findTheWinner(int n, int k) {
        List<Integer> list=new ArrayList<>();
        for(int i=0;i<n;i++){
            list.add(i+1);
        }
        int i=0;
        while(n>1){ 
            i=(i+k-1)%n; //cyclic, when reach end, start from head
            list.remove(i);
            n--;
        } //then n=1
        return list.get(0);
    }
}

390. Elimination Game
视频讲解

 public int lastRemaining(int n) {
        return n==1?1:2*(n/2+1-lastRemaining(n/2));
    }
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值