看代码

UTF-8 编码验证

http://www.nowcoder.com/questionTerminal/a41ac365553e4646aa84fd9b7dad92f9

UTF-8 编码验证
UTF-8 编码验证playground


import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        while (sc.hasNext()) {

            String[] str = sc.next().split(",");
            short[] arr = new short[str.length];
            for (int i = 0; i < str.length; i++) {
                short n = Short.valueOf(str[i]);
                arr[i] = (short)(n & 0xFF);
            }

            boolean illegal = true;
            for (int i = 0; i < arr.length; i++) {
                short b = arr[i];
                if (b >= 0 && b < 128) {
                    continue;
                } else if (b >= 192 && b < 224) {
                    if (i + 1 >= arr.length) {
                        illegal = false;
                        break;
                    }

                    illegal = arr[i + 1] >= 128 && arr[i + 1] < 192;
                    if (!illegal)
                        break;

                    i += 1;
                } else if (b >= 224 && b < 240) {
                    if (i + 2 >= arr.length) {
                        illegal = false;
                        break;
                    }

                    illegal = arr[i + 1] >= 128 && arr[i + 1] < 192 && arr[i + 2] >= 128 && arr[i + 2] < 192;
                    if (!illegal)
                        break;

                    i += 2;
                } else if (b >= 240 && b < 248) {
                    if (i + 3 >= arr.length) {
                        illegal = false;
                        break;
                    }

                    illegal = arr[i + 1] >= 128 && arr[i + 1] < 192 && arr[i + 2] >= 128 && arr[i + 2] < 192 &&
                            arr[i + 3] >= 128 && arr[i + 3] < 192;

                    if (!illegal)
                        break;

                    i += 3;
                } else {
                    illegal = false;
                    break;
                }
            }

            System.out.println(illegal);
        }
    }
}
全部评论

相关推荐

头像
10-22 19:18
上海大学 后端
jopajhhdjwnqk:水印都叠杀人书了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务