我是靠谱客的博主 健康白开水,最近开发中收集的这篇文章主要介绍Powers of Two,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

第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));
    }
}

 

最后

以上就是健康白开水为你收集整理的Powers of Two的全部内容,希望文章能够帮你解决Powers of Two所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(47)

评论列表共有 0 条评论

立即
投稿
返回
顶部