求大神解答CVTE数据切割那个编程题答案

如题#广州视源电子科技股份有限公司#
全部评论
import java.util.Scanner; /*  * 题目:给定一个整数n和一个整数m,将n按照位分割成多个数字,使得这多个数字的和最接近m,  *     例如n=654321,m=50,则最大值为48(6+5+4+32+1)  * */ public class Main {     // 求最大值     public static Integer plimit(Integer n, Integer m) {         if (n < m)             return n;         Integer add = 0; //把所有的位加起来的和         Integer maxNum = 0;   //最终所求结果         Integer count = 0;    //辅助计数器,计算每个子数组中按位加起来的的和         Integer madd = 0;    //辅助计数,把每个子数组中的数字表示成十进制         Integer mc = 0;      //辅助计数,把每个子数组中的数字表示成十进和其他位按位加起来的总和         int a = 0, b = 0;    //标记子数组第一位和最后一位的指针         String nstr = n.toString();    //将n转化成字符串         String mstr = m.toString();   //将m转化字符串         int nlength = nstr.length(); // n的长度         int mlength = mstr.length(); // m的长度         int[] narr = new int[nlength]; // 新建一个数组用来保存num每一位的数字         for (int i = 0; i < nlength; i++) {             Character ch = nstr.charAt(i); // 遍历nstr将每一位数字添加到narr             narr[i] = Integer.parseInt(ch.toString());         }         for (int i = 0; i < nlength; i++) {             add += narr[i];         }         if (add < m){             for (int i = 2; i <= mlength; i++) {                 a = 0;                 b = i - 1;                 while (b < nlength) {                     for (int j = a; j <=b; j++) {                         //System.out.println("j="+j);                         count += narr[j];                         madd = madd + (int) (narr[j] * Math.pow(10, (b - j)));                         a++;                     }                     mc = (add - count) + madd;                     //System.out.println("mc="+mc);                     if (mc > maxNum && mc < m) {                         maxNum = mc;                     }                     b++;                     a = b - i + 1;                     madd=0;                     count=0;                     //System.out.println("a=  b="+a+" "+b);                 }             }         }         return maxNum;     }     public static void main(String[] args) {         Scanner in = new Scanner(System.in);         Integer n = in.nextInt();         Integer m = in.nextInt();         System.out.println(plimit(n, m));     } } /* 例一:      输入:   654321   50      输出:   48   例一:      输入:   654321   661      输出:   600  */
点赞 回复 分享
发布于 2017-09-03 13:05
原来题目不一样
点赞 回复 分享
发布于 2017-09-02 23:27
多谢分享
点赞 回复 分享
发布于 2017-09-02 22:33
http://blog.csdn.net/xiao_dondon/article/details/77804072
点赞 回复 分享
发布于 2017-09-02 22:03
同求
点赞 回复 分享
发布于 2017-09-02 21:59

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务