Secret Origins

本文介绍了一个算法挑战,即找到大于给定整数N的下一个整数,该整数具有与N相同的二进制1的数量。文章提供了一种高效的方法,使用位操作而非暴力搜索。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

This is the tale of Zephyr, the greatest time traveler the world will never know. Even those who are aware of Zephyr's existence know very little about her. For example, no one has any clue as to which time period she is originally from.

But we do know the story of the first time she set out to chart her own path in the time stream. Zephyr had just finished building her time machine which she named - "Dokhina Batash". She was making the final adjustments for her first trip when she noticed that a vital program was not working correctly. The program was supposed to take a number N, and find what Zephyr called its Onoroy value.

The Onoroy value of an integer N is the number of ones in its binary representation. For example, the number 13 (11012) has an Onoroy value of 3. Needless to say, this was an easy problem for the great mind of Zephyr. She solved it quickly, and was on her way.

You are now given a similar task. Find the first number after N which has the same Onoroy value as N.

Input

Input starts with an integer T (≤ 65), denoting the number of test cases.

Each case begins with an integer N (1 ≤ N ≤ 109).

Output

For each case of input you have to print the case number and the desired result.

Sample Input

5

23

14232

391

7

8

Sample Output

Case 1: 27

Case 2: 14241

Case 3: 395

Case 4: 11

Case 5: 16

分析:求解n之后第一个和它二进制相同的数,暴力法,真是超时。。。。。

膜大佬的位运算方案:

可以通过一下步骤:

(1)求出最低位的1开始的连续的1的区间(0101110->0001110) 

(2)将这一区间全部变为0,并将区间左侧的那个0变为1(0101110->0110000)

(3)将第(1)步里取出的区间右移,直到剩下的1的个数减少了1个(0001110->0000011)

(4)将第(2)步和第(3)步的结果按位取或(0110000|0000011=0110011)

对于为零的整数,N&(-N)的值就是将其最低位的1独立出来后的值。这是由于计算机中负数采用二进制补码表示,-N实际上对应于(~N)+1(将N按位取反然后加上1)。

将最低位的1取出后,设它为x。那么通过计算y=N+x,就将N从最低位的1开始的连续的1都置为0了。我们来比较一下~y和N。在N中加入x后没有变化的位,在~y中全部取相反的值。而最低位1开始的连续区间在~y中依然是1,区间左侧的那个0在~y中也依然是0。于是通过计算z=N&~y就得到了最低位1开始的连续区间。比如如果N=0101110,则x=0000010,y=0110000,z=0001110。

同时,y也恰好是第(2)步要求的值那么首先将z不断右移,知道最低位为1,这通过计算z/x即可完成。这样再将z/x右移1位就得到了第(3)要求的值。

import java.util.*;
 public  class Main{
    static Scanner in = new Scanner(System.in);
    public static void main(String args[]){ 
        int k=in.nextInt();  
        int ca = 0;
        while(k-->0){   
        	ca++;
            int n = in.nextInt();  
            int x = n & -n, y = n + x;  
            n = ((n & ~y) / x >> 1) | y;  
          System.out.println("Case "+ca+": "+ n);  
      }     
    }    
}

瑟瑟发抖。。。。根本想不到。。。
import os from flask import Flask, render_template, request, redirect, sessions, jsonify from flask_socketio import SocketIO, emit # 导入socketio包 name_space = '/websocket' app = Flask(__name__) app.secret_key = 'secret!' socketio = SocketIO(app, cors_allowed_origins='*') client_query = [] max_restruct_count = 3 current_restruct_count = 0 queue = [] restr_msg = {} is_restructing = False @socketio.on('connect') def on_connect(): client_id = request.sid client_query.append(client_id) socketio.emit('abb', 'hi') print('有新连接id=%s接加入, 当前连接数%d' % (client_id, len(client_query))) global is_restructing, current_restruct_count if current_restruct_count == 0: socketio.emit('status', '0') else: socketio.emit('status', '1') @socketio.on('disconnect') def on_disconnect(): client_query.remove(request.sid) print('有连接id=%s接退出, 当前连接数%d' % (request.sid, len(client_query))) @socketio.on('abc') def on_message(abc): print(abc) def check(): global current_restruct_count if current_restruct_count == 0: socketio.emit('status', '0') else: socketio.emit('status', '1') @socketio.on('output') def start_restruct(dch): return 1 @app.route('/restruct', methods=['POST']) def restruct(): return jsonify({"code": 200, "msg": "processing"}) @app.route('/show_dirs', methods=['POST']) def show_dirs(): des_dir = 'moxingku' dirs_list = [] for root, dirs, files in os.walk(des_dir): for dir_name in dirs: if os.path.join(root, dir_name).count(os.sep) == 1: dirs_list.append(dir_name) return jsonify({"code": 200, "dirs_list": dirs_list}) if __name__ == '__main__': socketio.run(app, host='0.0.0.0', port=5000, debug=False)#allow_unsafe_werkzeug=True) 这段代码如何改可以将开发环境变成生产环境
07-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值