JAVA-二进制分解

import java.util.Stack;
import java.lang.Integer;
import java.util.Scanner;
public class test1
{
	static void convert(int num)
	{
		int result = num;
		int consult = num;
		int remainder;
		Stack<Integer> st = new Stack<Integer>();
		while(consult != 0)
		{
			consult = consult/2;
			remainder = num%2;
			num = consult;
			st.push(remainder);
		}
		int[] a = new int[st.size()];
		int k = 0;
		while(!st.empty())
		{		
			a[k] = st.pop();
			k++;
		}
		for(int i = 0;i<a.length;i++)
		{
			System.out.print(a[i]);
		}
		System.out.println("");
		String n = "2^";
		String s = "";
		for(int i = 0;i < a.length;i++)
		{
			if(a[i]!=0)
				{	
					s = s + n + (a.length-i-1)+"+";
				}
		}
		s = s.substring(0,s.length()-1);
		System.out.println(result+"="+s);
	}

	
	public static void main(String[] args)
	{
		while(true)
		{
			Scanner sc = new Scanner(System.in);
			int num = sc.nextInt();
			convert(num);
			System.out.println();
		}
	}
}

猜你喜欢

转载自blog.csdn.net/Tommy5553/article/details/80903969