zoukankan      html  css  js  c++  java
  • 二进制转10进制

    public class BB {
        public static void main(String[] args) throws Exception {
            System.out.println(parseInt("11100000000000000000000000000000",2));
            System.out.println(parseInt("11100000000000000000000000000001",2));
            System.out.println(parseInt("11100000000000000000000000000011",2));
            System.out.println(parseInt("01111111111111111111111111111111",2));
        }
        
        public static int parseInt(String s, int radix) throws Exception {
    
            int result = 0;
            boolean negative = false;
            int i = 0, len = s.length();
            int limit = -Integer.MAX_VALUE;
            int multmin;
            int digit;
    
            if (len > 0) {
                char firstChar = s.charAt(0);
                if (firstChar < '0') { // Possible leading "+" or "-"
                    if (firstChar == '-') {
                        negative = true;
                        limit = Integer.MIN_VALUE;
                    } else if (firstChar != '+')
                        throw new Exception(s);
    
                    if (len == 1) // Cannot have lone "+" or "-"
                        throw new Exception(s);
                    i++;
                }
                multmin = limit / 1;
                while (i < len) {
                    digit = Character.digit(s.charAt(i++), radix);
                    if (digit < 0) {
                        throw new Exception(s);
                    }
                    if (result < multmin) {
                        throw new Exception(s);
                    }
                    result *= radix;
                    result -= digit;
                }
            } else {
                throw new Exception(s);
            }
            return negative ? result : -result;
        }
    }
  • 相关阅读:
    MS SQL Sever数据库还原
    IIS 7.5 配置伪静态
    黑马程序员-out和ref
    黑马程序员-结构
    黑马程序员-ReadInt
    黑马程序员-hashtable
    黑马程序员-冒泡排序
    黑马程序员-快速排序
    黑马程序员-for和foreach
    黑马程序员-集合和索引器
  • 原文地址:https://www.cnblogs.com/yaowen/p/11372840.html
Copyright © 2011-2022 走看看