给定两个整数A和B ,代表一张纸的长度和宽度,任务是通过重复将面积减半直到它不能被2整除,找到可以从中生成的最大张数。
例子:
Input: A = 5, B = 10
Output: 2
Explanation:
- Initial Area = 5 * 10. Count = 0.
- Area / 2 = 5 * 5. Count = 2.
Input: A = 1, B = 8
Output: 8
处理方法:按照以下步骤解决问题:
- 计算提供的初始表的总面积。
- 现在,继续将工作表的面积除以2,直到它变成奇数。
- 每次除法后,将计数增加到其值的两倍。
- 最后,打印获得的计数。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to calculate the
// maximum number of sheets
// possible by given operations
int maxSheets(int A, int B)
{
int area = A * B;
// Initial count of sheets
int count = 1;
// Keep dividing the
// sheets into half
while (area % 2 == 0) {
// Reduce area by half
area /= 2;
// Increase count by twice
count *= 2;
}
return count;
}
// Driver Code
int main()
{
int A = 5, B = 10;
cout << maxSheets(A, B);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG
{
// Function to calculate the
// maximum number of sheets
// possible by given operations
static int maxSheets(int A, int B)
{
int area = A * B;
// Initial count of sheets
int count = 1;
// Keep dividing the
// sheets into half
while (area % 2 == 0)
{
// Reduce area by half
area /= 2;
// Increase count by twice
count *= 2;
}
return count;
}
// Driver Code
public static void main(String args[])
{
int A = 5, B = 10;
System.out.println(maxSheets(A, B));
}
}
// This code is contributed by jana_sayantan.
Python3
# Python program for the above approach
# Function to calculate the
# maximum number of sheets
# possible by given operations
def maxSheets( A, B):
area = A * B
# Initial count of sheets
count = 1
# Keep dividing the
# sheets into half
while (area % 2 == 0):
# Reduce area by half
area //= 2
# Increase count by twice
count *= 2
return count
# Driver Code
A = 5
B = 10
print(maxSheets(A, B))
# This code is contributed by rohitsingh07052.
C#
// C# program for the above approach
using System;
class GFG
{
// Function to calculate the
// maximum number of sheets
// possible by given operations
static int maxSheets(int A, int B)
{
int area = A * B;
// Initial count of sheets
int count = 1;
// Keep dividing the
// sheets into half
while (area % 2 == 0)
{
// Reduce area by half
area /= 2;
// Increase count by twice
count *= 2;
}
return count;
}
// Driver Code
public static void Main()
{
int A = 5, B = 10;
Console.WriteLine(maxSheets(A, B));
}
}
// This code is contributed by chitranayal.
Javascript
输出:
2
时间复杂度: O(log 2 (A * B))
辅助空间: O(1)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。