【题解】B. Split a Number⭐⭐⭐ 【思维 高精度】

B. Split a Number

Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn’t fit in the Dima’s bookshelf.

To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip.

Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain.

Input

The first line contains a single integer l (2≤l≤100000) — the length of the Dima’s favorite number.

The second line contains the positive integer n initially written on the strip: the Dima’s favorite number.

The integer n consists of exactly l digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip.

Output

Print a single integer — the smallest number Dima can obtain.

Examples

inputCopy
7
1234567
outputCopy
1801
inputCopy
3
101
outputCopy
11

Hint

In the first example Dima can split the number 1234567 into integers 1234 and 567. Their sum is 1801.

In the second example Dima can split the number 101 into integers 10 and 1. Their sum is 11. Note that it is impossible to split the strip into “1” and “01” since the numbers can’t start with zeros.




题意:

给你一串树, 要求切两块一块前导不能为0且不能非空, 求最小的和

题解:

简单想一下要求最小肯定优先要从中间来切, 但是要分类讨论中间为0的情况以及位数为奇偶的情况
两种切法都试一下, 然后找到最近的非0位, 比较一下那种和更小就好了

经验小结:

第一次用Java大数写题, 好方便噢


import java.math.BigInteger;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int l = input.nextInt();
        String num = input.next();
        BigInteger x, y, sum;

        int cnt1 = (l-1)>>1, cnt2 = (l+1)>>1;            //只可能有这两种分法
        while (cnt1!=l && num.charAt(cnt1)=='0') ++cnt1; //向右扫直至不是0
        while (num.charAt(cnt2) == '0') --cnt2;          //向左扫直至不是0

        if(cnt2 == 0)
            x = new BigInteger("0");
        else
            x = new BigInteger(num.substring(0, cnt2));
        y = new BigInteger(num.substring(cnt2, l));
        sum = x.add(y);

        if(cnt1 == l) y = new BigInteger("0");
        else y = new BigInteger(num.substring(cnt1, l));
        if(cnt1==0) ++cnt1;                             //只有2位的特殊情况
        x = new BigInteger(num.substring(0, cnt1));
        sum = sum.min(x.add(y));                        //两种分法进行比较

        System.out.println(sum);
        input.close();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值