General solution for remove X (d*logn) d<=10


  • 0
    A
    class Solution {
        public int newInteger(int n) {
            int low = 1, high = Integer.MAX_VALUE;
            while (low <= high){
                int mid = low + (high - low) / 2;
                if (tooLarge(mid, n)){
                    high = mid - 1;
                }else{
                    low = mid + 1;
                }
            }
            return low;
        }
        boolean tooLarge(int val, int n){
            String digits = "" + val;
            int sum = 0;
            int self = 0;
            for (int i = 0; i < digits.length(); i++){
                int digit = digits.charAt(i) - '0';
                
                if (digit > 0){
                    sum += (digit) * getNum(digits.length() - i - 1);                  
                }
                if (digit == 9){
                    sum += i != digits.length() - 1 ? Integer.parseInt(digits.substring(i + 1)) + 1 : 1;
                    break;
                }
            }
            
            return val - sum >= n;
        }
        int getNum(int v){
            return (int)Math.pow(10, v) - (int)Math.pow(9, v);
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.