日期:2014-05-20 浏览次数:21052 次
public static void main(String args[]){ Scanner input = new Scanner(System.in); int inputNumber = input.nextInt(); erjinzhi(inputNumber); } public static String erjinzhi(int a){ boolean flag = true; boolean isZhengshu = (a>=0?true:false); if(!isZhengshu){ a = a&0xffff; } int temp = Math.abs(a); StringBuffer sb = new StringBuffer(); while(flag){ int yushu = temp%2; sb.append(yushu); temp = temp/2; if(temp == 0){ flag = false; } } StringBuffer result = new StringBuffer(); for(int i=0;i<sb.length();i++){ result.append(sb.charAt(sb.length()-1-i)); } System.out.print(result); return result.toString(); }
------解决方案--------------------
都是基础题,LZ应该好好思考
还是贴下代码吧。。。
import java.util.Scanner; public class Test { public static void main(String[] args) { test1(); test2(); } //二进制 static void test1(){ System.out.print("二进制 输入一个数: "); Scanner scanner = new Scanner(System.in); try { int num = scanner.nextInt(); int numTemp = num; //System.out.println(num + "的二进制数" + Integer.toBinaryString(num)); StringBuffer sBuffer = new StringBuffer(); while(numTemp != 0){ int value = numTemp % 2; sBuffer.append(value); numTemp /= 2; } System.out.println(num + "的二进制数" + sBuffer.reverse().toString()); } catch (Exception e) { System.out.println("输入数不合法"); } } //质数 static void test2(){ System.out.print("质数 输入一个数: "); Scanner scanner = new Scanner(System.in); try { int num = scanner.nextInt(); for(int i = 2;i < Math.sqrt(num);i++){ if(num % i == 0){ System.out.println(num + "不是质数"); return; } } System.out.println(num + "是质数"); } catch (Exception e) { System.out.println("输入数不合法"); } } }