package bitsgoroku; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Bitsugoroku { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); try { int now = 1; List resultList = new ArrayList(); List backList = new ArrayList<>(); while (now != n) { int bitCount = changeBinary(now); if ((now + bitCount) > n) {// nを超えてしまう時 resultList.add(now); if (backList.contains(now)) { break; } backList.add(now); now -= bitCount; } else if ((now + bitCount) <= n) {// nを超えない時 resultList.add(now); now += bitCount; } } if (now != n) { System.out.println("-1"); } else { resultList.add(now); System.out.println(resultList.size()); } } catch (Exception e) { System.out.println(e); } } private static int changeBinary(int result) { String bin = Integer.toBinaryString(result); String[] binArray = bin.split(""); // 2進数の1の数を数える int binCount = 0; for (String sss : binArray) { if (sss.equals("1")) { binCount++; } } return binCount; } }