幂方分解

蓝桥杯 ALGO-12 幂方分解

问题描述
  任何一个正整数都可以用2的幂次方表示。例如:
  137=27+23+20
  同时约定方次用括号来表示,即ab 可表示为a(b)。
  由此可知,137可表示为:
  2(7)+2(3)+2(0)
  进一步:7= 22+2+20 (21用2表示)
  3=2+20
  所以最后137可表示为:
  2(2(2)+2+2(0))+2(2+2(0))+2(0)
  又如:
  1315=210 +28 +25 +2+1
  所以1315最后可表示为:
  2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)
输入格式
  输入包含一个正整数N(N<=20000),为要求分解的整数。
输出格式
  程序输出包含一行字符串,为符合约定的n的0,2表示(在表示中不能有空格)

方法一:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        in.close();
        div(n);
    }

    private static void div(int n) {
        if (n == 0) {
            System.out.print(0);
            return;
        }
        
        char[] cs = Integer.toBinaryString(n).toCharArray();
        //这个数组从下标0开始到数组结尾,存储的是二进制从头到尾
        boolean book= false;
        for (int i = 0; i < cs.length; i++) {
            if (cs[i] == '1') {
                if (book) {
                    if (cs.length - i - 1 == 1) {
                        System.out.print("+2");
                    } else {
                        System.out.print("+2(");
                        div(cs.length - 1 - i);
                        System.out.print(")");
                    }
                } else {
                    if (cs.length - i - 1 == 1) {
                        System.out.print(2);
                    } else {
                        System.out.print("2(");
                        div(cs.length - 1 - i);
                        System.out.print(")");
                    }
                    book = true;
                }
            }
        }
    }
}

结果示意图:

方法二:


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		 Scanner input = new Scanner(System.in); 
		 int n = input.nextInt(); 
		 fun(n);
	}
	
	 public static void fun(int n){
		 int value = 0; 
		 if(n==1){ 
			 System.out.print("2(0)");
			 return; 
		 } 
		 if(n==2){
			System.out.print("2"); 
			return; 
		 } 
		 for(int i=0;i<15;i++){
			if(n>=Math.pow(2,i) && n<Math.pow(2,i+1)){ 
				value = i;
				break;
			}		
		 } 
		if(value==0){
			System.out.print("2(0)"); 
		}else if(value==1){
			System.out.print("2");
		}else { 
			System.out.print("2("); 
			fun(value);
	    	System.out.print(")");
		 }
		if((int)(n - Math.pow(2,value))!=0){
			System.out.print("+"); 
			fun((int)(n - Math.pow(2,value)));
		}
	}
}

结果示意图:

原文地址:https://www.cnblogs.com/AIchangetheworld/p/12787634.html