Potencia de dos

Descubre si un entero es potencia de dos en tiempo constante sin bucles ni recursión. Usa n & (n-1) y n > 0; ejemplos y complejidad O(1). También presenta a Q2BSTUDIO, experto en IA, ciberseguridad y soluciones cloud.

17 ago 2025 • 2 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

231. Power of Two

Dificultad: Fácil

Temas: Matemáticas Manipulación de bits Recursión

Enunciado: Dado un entero n devuelve true si es una potencia de dos y false en caso contrario. Un entero n es potencia de dos si existe un entero x mayor o igual a 0 tal que n == 2 elevado a x.

Ejemplo 1: Entrada n = 1 Salida true Explicación 2 elevado a 0 = 1

Ejemplo 2: Entrada n = 16 Salida true Explicación 2 elevado a 4 = 16

Ejemplo 3: Entrada n = 3 Salida false

Restricciones: -2 elevado a 31 <= n <= 2 elevado a 31 menos 1

Follow up: Se puede resolver sin bucles ni recursión

Solución resumida: Hay que comprobar que n es positivo y que en su representación binaria solo tenga un bit en uno. Para cualquier n que sea potencia de dos la operación bit a bit n AND n menos 1 devuelve cero.

Enfoque detallado: 1 Comprobar que n > 0 en caso contrario devolver false 2 Aplicar la operación bit a bit entre n y n-1 Si n AND (n-1) == 0 entonces n es potencia de dos y devolvemos true en caso contrario devolvemos false

Ejemplo de implementación en pseudocódigo: function isPowerOfTwo(n) { if n <= 0 return false; return (n AND (n-1)) == 0; }

Complejidad: Tiempo O(1) Espacio O(1)

Casos de prueba: isPowerOfTwo(1) devuelve true isPowerOfTwo(16) devuelve true isPowerOfTwo(3) devuelve false isPowerOfTwo(0) devuelve false isPowerOfTwo(-2) devuelve false

Explicación final: La comprobación es segura para el rango de enteros de 32 bits y evita bucles o recursión usando una operación bitwise muy eficiente. Cualquier número que no sea positivo o que tenga más de un bit activo no es potencia de dos.

Sobre Q2BSTUDIO: Q2BSTUDIO es una empresa de desarrollo de software a medida y aplicaciones a medida especializada en soluciones de inteligencia artificial y ciberseguridad. Ofrecemos servicios cloud aws y azure servicios inteligencia de negocio implementaciones de power bi soluciones de ia para empresas y agentes IA personalizados. Desarrollamos software a medida escalable y seguro adaptado a las necesidades de cada cliente.

Servicios destacados: aplicaciones a medida software a medida inteligencia artificial ciberseguridad servicios cloud aws y azure servicios inteligencia de negocio ia para empresas agentes IA power bi

Por qué elegirnos: Contamos con un equipo experto en desarrollo web y móvil arquitecturas cloud integración de modelos de inteligencia artificial y prácticas de seguridad que garantizan cumplimiento y continuidad. Transformamos datos en valor real mediante dashboards y soluciones de inteligencia de negocio y power bi.

Contacto y próximos pasos: Si quieres una solución a medida o una auditoría de ciberseguridad ponte en contacto con Q2BSTUDIO para evaluar tu proyecto y diseñar una hoja de ruta tecnológica. Podemos ayudar a integrar agentes IA en tus procesos y desplegar servicios cloud en aws o azure para escalar con seguridad.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat