一、Description
Suppose you are reading byte streams from any device, representing IP addresses. Your task is to convert a 32 characters long sequence of '1s' and '0s' (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. To convert binary numbers to decimal numbers remember that both are positional numerical systems, where the
first 8 positions of the binary systems are:
27 26 25 24 23 22 21 20 128 64 32 16 8 4 2 1
Input
The input will have a number N (1<=N<=9) in its first line representing the number of streams to convert. N lines will follow.
Output
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.
二、题解
今天见鬼了,碰到这么多水题。这题就是在采用什么读取输入流时纠结了一下,最后还是用了SC,然后再用字符串的性质解决了问题。
三、java代码
二、题解
今天见鬼了,碰到这么多水题。这题就是在采用什么读取输入流时纠结了一下,最后还是用了SC,然后再用字符串的性质解决了问题。
三、java代码
import java.util.Scanner; public class Main { public static int transform(String s){ int sum=0; if(s.charAt(0)=='1') sum+=128; if(s.charAt(1)=='1') sum+=64; if(s.charAt(2)=='1') sum+=32; if(s.charAt(3)=='1') sum+=16; if(s.charAt(4)=='1') sum+=8; if(s.charAt(5)=='1') sum+=4; if(s.charAt(6)=='1') sum+=2; if(s.charAt(7)=='1') sum+=1; return sum; } public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n,i; String s; n=sc.nextInt(); for(i=0;i<n;i++){ s=sc.next(); System.out.println(transform(s.substring(0,8))+"."+transform(s.substring(8,16))+"." +transform(s.substring(16,24))+"."+transform(s.substring(24,32))); } } }