ECNU 1002 IP Address

ECNU 1002 IP Address

链接

https://acm.ecnu.edu.cn/problem/1002

题目

单点时限: 2.0 sec

内存限制: 256 MB

Suppose you are reading byte streams from any device, representing IP addresses. Your task is to convert a 32 characters long sequence of s and s (bits) to a dotted decimal format. A dotted decimal format for an IP address is form by grouping 8 bits at a time and converting the binary representation to decimal representation. Any 8 bits is a valid part of an IP address.10

To convert binary numbers to decimal numbers remember that both are positional numerical systems, where the first 8 positions of the binary systems are:

输入格式
The input will have a number N(1-9) in its first line representing the number of streams to convert. lines will follow.

输出格式
The output must have N lines with a doted decimal IP address. A dotted decimal IP address is formed by grouping 8 bit at the time and converting the binary representation to decimal representation.

样例
input
4
00000000000000000000000000000000
00000011100000001111111111111111
11001011100001001110010110000000
01010000000100000000000000000001
output
0.0.0.0
3.128.255.255
203.132.229.128
80.16.0.1

思路

英文题目,不是太难,就是把给的字符串转化为ip地址再输出。
这里采用了一个tag用于标记权值,12864往后,flag用于标记属于第几块,这道题发散一下也就是一道进制转换的题目。
当tag到8的时候(还未计算),就代表当前这一段结束了,换下一段并重新计算权值。

代码

  public static void fun() {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    for (int i = 0; i < n; i++) {
      String str = sc.next();
      int[] a = new int[4];
      StringBuffer sb = new StringBuffer(str);
      int[] weight = new int[]{128, 64, 32, 16, 8, 4, 2, 1};
      int flag = 0;
      int tag = 0;
      for (int j = 0; j < 32; j++) {
        int temp = 1;
        if ((sb.charAt(j) == '0')) {
          temp = 0;
        }
        a[flag] += weight[tag] * temp;
        tag++;
        if (tag == 8) {
          tag = 0;
          flag++;
        }
      }
      System.out.println(a[0] + "." + a[1] + "." + a[2] + "." + a[3]);
    }
  }
posted @ 2021-01-21 15:27  cheng102e  阅读(72)  评论(0编辑  收藏  举报