华为OD:求字符串中所有整数的最小和

输入字符串s,输出s中包含所有整数的最小和。

说明:

字符串s,只包含a-z A-Z+-;

合法的整数包括:

  1. 正整数一个或者多个0-9组成,如 0 2 3 002 202
  2. 负整数负号-开头,数字部分由一个或者多个0-9组成,如-0 -012 -23 -00023

输入描述:

包含数字的字符串

输出描述:

所有整数的最小和

用例:

|----|----------|
| 输入 | bb1234aa |
| 输出 | 10 |
| 说明 | 无 |

Java算法源码:

java 复制代码
import java.math.BigInteger;
import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.println(getResult(sc.nextLine()));    
    }
    public static String getsult(String s){
        boolean isNegative=false;
        StringBuilder negative =new StringBuilder();
        BinInteger ans = new BigInteger("0");
        for(int i=0;i<s.length();i++){
            char c = s.charAt(i);
            if(isNagative){
                negative.append(c);            
            }else{
                ans = ans.add(new BigInteger(c+""));            
            }        
        }else{
            if(isNegative){
                ans = ans.subtract(new BigInteger(negative.toString()));
                negative = new StringBuilder();            
            } 
            isNegative = c =='-';       
        }    
    }
    if(negative.length()>0){
        ans=ans.subtract(new BigInteger(negative.toString()));    
    }
    return ans.toString();
}
}
相关推荐
❥ღ Komo·8 小时前
K8s服务发现与DNS解析全解析
java·开发语言
g***B73810 小时前
Java 工程复杂性的真正来源:从语言设计到现代架构的全链路解析
java·人工智能·架构
期待のcode12 小时前
MyBatisX插件
java·数据库·后端·mybatis·springboot
yaoh.wang14 小时前
力扣(LeetCode) 13: 罗马数字转整数 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
T1ssy14 小时前
布隆过滤器:用概率换空间的奇妙数据结构
算法·哈希算法
醇氧14 小时前
【Windows】优雅启动:解析一个 Java 服务的后台启动脚本
java·开发语言·windows
sunxunyong14 小时前
doris运维命令
java·运维·数据库
菜鸟起航ing14 小时前
Spring AI 全方位指南:从基础入门到高级实战
java·人工智能·spring
古城小栈15 小时前
Docker 多阶段构建:Go_Java 镜像瘦身运动
java·docker·golang
hetao173383715 小时前
2025-12-12~14 hetao1733837的刷题笔记
数据结构·c++·笔记·算法