🌞188 · 插入五

题目描述

给定一个数字,在数字的任意位置插入一个5,使得插入后的这个数字最大。


示例

输入:  a = 234
输出: 5234

题解

public class Solution {
    /**
     * @param a: A number
     * @return: Returns the maximum number after insertion
     */
    public int InsertFive(int a) {
        // write your code here
        if(a<0){
            String str = ""+a;
            int b = -1;
            for (int i = 1; i < str.length(); i++) {
                b = i;
                String as = ""+str.charAt(i);
                int inas = Integer.valueOf(as);
                if (inas>5){
                    break;
                }
            }
            StringBuilder s = new StringBuilder(str);
            s.insert(b,'5');
            int c = Integer.valueOf(s.toString());
            return c;
        }
        String str = ""+a;
        int b = -1;
        for (int i = 0; i < str.length(); i++) {
            b = i;
            String as = ""+str.charAt(i);
            int inas = Integer.valueOf(as);
            if (inas<5){
                break;
            }
        }
        StringBuilder s = new StringBuilder(str);
        s.insert(b,'5');
        int c = Integer.valueOf(s.toString());
        return c;
    }
}
posted @ 2021-12-16 21:21  两小无猜  阅读(122)  评论(0编辑  收藏  举报