2016年7月4日 星期一

Q10019 : Funny Encryption Method


https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=960

import java.util.*;

public class Main {

 public static void main(String[] args) {
  Scanner scn = new Scanner(System.in);
  int n = scn.nextInt();
  for (int i = 0; i &lt n; i++) {
   String str = scn.next();
   System.out.printf("%d %d\n", Integer.bitCount(Integer.parseInt(str)),
     Integer.bitCount(Integer.parseInt(str, 16)));
  }
 }

 /* 
    題目:Q10019 : Funny Encryption Method
    作者:1010
    時間:西元 2016 年 7 月 */
}


困難度 
Java 內有提供轉二進位函數
public class Test {
 public static void main(String args[]) {
  int n = 8;
  System.out.println(Integer.toBinaryString(n));

 }

}
Integer 類別有 static parseInt() 方法,可以將字串 (string) 中的整數轉換 int 型態的數值 (value)
static int parseInt(String s, int radix) 可將字串解析為指定進位的整數


public class Test {
 public static void main(String args[]) {
  String s = "22";
  int i1 = Integer.parseInt(s);
  int i2 = Integer.parseInt(s, 16);
  System.out.println(i1);
  System.out.println(i2);

 }

}

利用 Integer.bitCount計算出二進位位元數 
public class Test {
 public static void main(String args[]) {
  int n = 170; // 10101010
  System.out.println("Value in binary: 10101010");
  System.out.println("Number of one bits: " + Integer.bitCount(n));
  System.out.println("Highest one bit: " + Integer.highestOneBit(n));
  System.out.println("Lowest one bit: " + Integer.lowestOneBit(n));
 }

}

}

沒有留言:

張貼留言