Powers of Two

求解最小2的幂次和
本文介绍了一个算法问题,即如何找到一个正整数N的最小数量的2的幂次表示。通过递归算法,文章展示了如何计算任意给定正整数N的最短2的幂次表示,包括示例代码实现。

第209周

题目1 : Powers of Two

时间限制:10000ms

单点时限:1000ms

内存限制:256MB

描述

Given a positive integer N, it is possible to represent N as the sum of several positive or negative powers of 2 (± 2k for some k). For example 7 can be represented as 22 + 21 + 20 and 23 + (-20).

Your task is to find the representation which contains the minimum powers of 2.

输入

One positive integer N.  

For 80% of the data: 1 <= N <= 100000  

For 100% of the data: 1 <= N <= 2000000000

输出

The minimum number of powers of 2.

样例输入

7

样例输出

2

模拟

import java.util.*;

public class Main{
    public static void main(String[]  args) {
        Scanner sc = new Scanner(System.in);
        
        long N = sc.nextLong();
        
        if ((N & (N - 1)) == 0) {// 最后一位变为0
            System.out.print(1);
            return;
        }
        
        int count = 0;
        
        while (N > 0) {
            
            long power = 1;
            
            while (power <= N) {
                power = power << 1;
            }
            
            long closest = Math.min(power - N, N - (power >>> 1));
            
            N = closest;
            
            count++;
        }
        
        System.out.print(count);
    }
}

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int N = scanner.nextInt();
        System.out.println(solve(N));
        scanner.close();
    }
    
    private static int solve(int n) {
    	return findMin(n);
    }
    
    private static int findMin(int n) {
    	int p = (int) (Math.log(n) / Math.log(2));
    	int m1 = (int) Math.pow(2, p);
    	int m2 = (int) Math.pow(2, p + 1);
    	if (m1 == n) return 1;
    	return 1 + Math.min(findMin(n - m1), findMin(m2 - n));
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值