首页 > 试题广场 >

最大数

[编程题]最大数
  • 热度指数:6035 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个包含大写英文字母和数字的句子,找出这个句子所包含的最大的十六进制整数,返回这个整数的值。数据保证该整数在int表示范围内

示例1

输入

"012345BZ16"

输出

1193051

说明

12345B对应十进制为1193051

备注:
0<字符串长度<=105
 public int solve (String s) {
        // write code here
    int max = 0;
	int sum = 0;
	for (int i = 0; i < s.length(); i++) {
		if (s.charAt(i) > 'F') {
			if (sum > max) {
				max = sum;
			}
			sum = 0;
			continue;
		}
	    int x = (s.charAt(i) >= 'A') ? 10 + s.charAt(i) - 'A' : s.charAt(i) - '0';
		sum = sum * 16 + x;
		}
		return max;
    }
发表于 2020-08-07 11:42:35 回复(0)
public int solve (String s) {
    List<String> listMatches = new ArrayList<String>();
    Matcher m = Pattern.compile("[0-9a-fA-F]+").matcher(s);
    while (m.find()) listMatches.add(m.group(0));
    Integer maxH = -1;
    for (String ele: listMatches) {
        if(ele.length() > 0){
            Integer t = Integer.parseInt(ele, 16);
            if(t > maxH) maxH = t;    
        }
    }
    return maxH.intValue();        
}
Java Regex 解法

发表于 2020-05-08 00:28:19 回复(1)
求合法连续子字符串的最大值,不断更新结果。遇到不合法大写字母,子字符串的开始Index和结束Index都要更新。
import java.util.*;


public class Solution {
    /**
     * 
     * @param s string字符串 
     * @return int整型
     */
    public int solve (String s) {
        // write code here
        int begin = 0;
        int end = 0;
        int result = 0;
        for(int i = 0; end < s.length(); i++) {
            if ( (Character.isDigit(s.charAt(i))) || (s.charAt(i) >= 'A' && s.charAt(i) <= 'F') ) {
                end++;
                result = Math.max(Integer.parseInt(s.substring(begin, end),16), result);
            } else {
                begin = i+1;
                end = begin;
            }
        }
        return result;
    }
}

发表于 2020-03-13 16:06:07 回复(1)