PSDN 1112: Minimum number of operations

Source: Internet
Author: User

Given a number, two methods of operation:

1, odd time plus 1 or minus 1

2, even when divided by 2

To change this number to the minimum operand required for 1


Consider the binary. Each number is converted into a binary number, and if the number is even, move right one bit, or if it is odd, determine whether the last three bits in the binary are three consecutive 1, which is + 1, not just-1.

In fact, at that time to get this problem is the first thought of BFS, but we all do bfs feel no meaning, the whim came up with this method. But there is no confidence ah, although the feeling is right, but can not prove that there will always be a problem. If someone finds an error, or can prove it, be sure to point it out.


#include <cstdio>
#include <iostream>
using namespace std;

int judge (int m) {
	int t=m,i=0;
	while (t!=1) {
		if (t&1) {
			if ((t>>1) &1 && (t>>2) &1) t+=1;
			else t-=1;
		}
		else t>>=1;
		i++;
	}
	return i;
}

int main () {
	int n;
	cin>>n;
	while (n--) {
		int m;
		cin>>m;
		Cout<<judge (M) <<endl;
	}
	return 0;
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.