Java编写任意long型整数字符串形式统计整数出现次数
以下是Java代码示例:
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
public class LongIntegerCount {
public static void main(String[] args) {
String longIntStr = "123456789012345678901234567890";
Map<Character, Integer> countMap = countLongInteger(longIntStr);
System.out.println("Long integer string: " + longIntStr);
System.out.println("Integer count:");
for (Map.Entry<Character, Integer> entry : countMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
public static Map<Character, Integer> countLongInteger(String longIntStr) {
Map<Character, Integer> countMap = new HashMap<>();
BigInteger longInt = new BigInteger(longIntStr);
String longIntAbsStr = longInt.abs().toString();
for (int i = 0; i < longIntAbsStr.length(); i++) {
char digit = longIntAbsStr.charAt(i);
countMap.put(digit, countMap.getOrDefault(digit, 0) + 1);
}
return countMap;
}
}
该程序定义了一个 countLongInteger 函数,接受一个字符串形式的长整数,返回一个字符到整数出现次数的映射。该函数首先将字符串转换为 BigInteger 类型,然后取其绝对值并转换为字符串形式。接着遍历该字符串中的每个数字字符,统计其出现次数并保存到映射中。最后在 main 函数中调用该函数并输出结果。
原文地址: https://www.cveoy.top/t/topic/bHZP 著作权归作者所有。请勿转载和采集!