Java examples for java.lang:Math Calculation
Determines if nNum is a power of 2.
/******************************************************************************* * Copyright (c) 2011 Matthias-M. Christen, University of Basel, Switzerland. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * // w w w. j a va 2 s .c o m * Contributors: * Matthias-M. Christen, University of Basel, Switzerland - initial API and implementation ******************************************************************************/ //package com.java2s; public class Main { /** * Determines if <var>nNum</var> is a power of 2. * * @param nNum * The integer to test * @return <code>true</code> iff <var>nNum</var> is a power of 2. */ public static boolean isPowerOfTwo(int nNum) { /* for (int i = 1; i <= nNum; i <<= 1) if (nNum == i) return true; return false; */ return nNum > 0 && ((nNum & (nNum - 1)) == 0); } }