zoukankan      html  css  js  c++  java
  • poj 2105 IP Address(水题)

    一、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代码
    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)));
        	}
        	
        }
    } 


  • 相关阅读:
    运维常见面试题
    python常见面试题
    常见面试题
    常用算法之‘归并排序’
    python库大全
    Springboot拦截器无效,解决办法
    Springboot 不返回页面,只反回文本
    SpringBoot 接收参数的几种常用方式(转载)
    mysql 查询每个分组的前几名
    Java中TimeZone类的常用方法
  • 原文地址:https://www.cnblogs.com/AndyDai/p/5135303.html
Copyright © 2011-2022 走看看