最后一位

https://www.nowcoder.com/practice/fae8632cfc64433989720bc01e09f382?tpId=90&tqId=30806&tPage=2&rp=2&ru=%2Fta%2F2018test&qru=%2Fta%2F2018test%2Fquestion-ranking

二分法找结果,主要就是给的值可能很大,最大值设为Integer.MAX_VALUE可能都不够

import java.util.*;
public class Main {
    public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            long in = sc.nextLong();
            System.out.println(Binary(in, 0, (long)1e18));
    }
    private static long getNiuSum(long num) {
            long ans = 0;
            while (num != 0) {
                ans += num;
                num /= 10;
            }
            return ans;
    }
    private static long Binary(long target,long from,long to) {
        while(from<to) {
            long mid=(from+to)/2;
            long temp=getNiuSum(mid);
            if(temp==target)
                return mid;
            if(temp>target)
                to=mid;
            if(temp<target)
                from=mid+1;    
        }
        return -1;
    }
}

还有一种非常简单的解法:从目标数变为源数字也是有一定规律的

总是111*a+11*b+1*c=x

string = input()
num,res=int(string),""
for i in range(len(string),0,-1):
    res+=str(num//int(i*'1'))
    num=num%int(i*'1')
print(res if int(res)<int(string) else -1)

 

posted @ 2019-05-18 10:03  LeeJuly  阅读(116)  评论(0)    收藏  举报