import std.stdio; import std.string, std.conv, std.array, std.algorithm; import std.uni, std.math; import core.bitop; void main(){ auto N = readln.chomp.to!int; auto ans = bfs(N); ans.writeln; } auto bfs(int N){ auto checked = new bool[](N + 1); auto d = new int[](N + 1); auto nxts = new Queue!(int)(N + 1); d[0] = 0, d[1] = 1; checked[0] = true, checked[1] = true; nxts.push(1); while(!nxts.isEmpty){ auto u = nxts.pop(); if(u == N) return d[u]; int st = popcnt(u); if(u + st <= N && !checked[u + st]){ d[u + st] = d[u] + 1; nxts.push(u + st); checked[u + st] = true; } if(u - st >= 0 && !checked[u - st]){ d[u - st] = d[u] + 1; nxts.push(u - st); checked[u - st] = true; } } return -1; } class Queue(T){ private T[] queue; private int head, tail, size; this(int N){ queue = new T[](N); head = 0, tail = 0; size = N; } bool isEmpty(){ return head == tail; } bool isFull(){ return head == (tail + 1) % size; } void push(T stuff){ if(this.isFull) throw new Exception("Stack is Full."); queue[tail] = stuff; tail = (tail + 1) % size; } auto pop(){ if(this.isEmpty) throw new Exception("Stack is Empty."); auto res = queue[head]; head = (head + 1) % size; return res; } auto top(){ return queue[head]; } }