zoukankan      html  css  js  c++  java
  • Java实现 蓝桥杯VIP 算法训练 幂方分解

    问题描述
    任何一个正整数都可以用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 幂方分解 {
    	   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();
    	        boolean isOutputFirst = false;
    	        for (int i = 0; i < cs.length; i++) {
    	            if (cs[i] == '1') {
    	                if (isOutputFirst) {
    	                    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(")");
    	                    }
    	                    isOutputFirst = true;
    	                }
    	            }
    	        }
    	    }
    
    
    }
    
    
  • 相关阅读:
    [YTU]_2536( C++ 长方体继承自矩形)
    [YTU]_2560(C++继承(改错题))
    [YTU]_2532(投简历)
    [YTU]_2621(B 继承 圆到圆柱体)
    stl
    noip2008双栈排序
    倍增入门水题
    noip模拟【ping】
    dp入门(LIS,LCS)
    【Luogu 1799】数列
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13079199.html
Copyright © 2011-2022 走看看